How do I delete a local git branch when it can't look up commit object in 'refs/heads'?

Viewed 5384

Lately every git pull I do gives me an error message like:

error: refs/heads/TestBranch123 does not point to a valid object!

These are old branches and I don't care, so I'd just like to delete them so I don't see the error anymore. When I try to delete the branch I can't for a similar error.

git branch -D TestBranch123

error: Couldn't look up commit object for 'refs/heads/TestBranch123'

2 Answers

8 years later, you won't get that error message anymore.

Adding --force will be enough:

git branch -d --force TestBranch123
# or
git branch -D TestBranch123

"git branch -D"(man) <branch> used to refuse to remove a broken branch ref that points at a missing commit, which has been corrected with Git 2.34 (Q4 2021).

See commit 597a977 (27 Aug 2021) by René Scharfe (rscharfe).
(Merged by Junio C Hamano -- gitster -- in commit ec8d24f, 08 Sep 2021)

branch: allow deleting dangling branches with --force

Reported-by: Ulrich Windl
Helped-by: Ævar Arnfjörð Bjarmason
Helped-by: Junio C Hamano
Signed-off-by: René Scharfe

git branch(man) only allows deleting branches that point to valid commits.
Skip that check if --force is given, as the caller is indicating with it that they know what they are doing and accept the consequences.
This allows deleting dangling branches, which previously had to be reset to a valid start-point using --force first.

git branch now includes in its man page:

branch irrespective of its merged status, or whether it even points to a valid commit.

Related