周汉成
周汉成

Reputation: 1445

How to delete a git working tree branch when its working directory has been removed?

I've removed its working directory, because this git working tree is no longer useful, then I git branch -D pubsub-sketch-tree at the directory of main repository. An error thrown:

error: Cannot delete branch 'pubsub-sketch-tree' checked out at '/Users/zhouhancheng/编程/github_own/sketch_worktree/pubsub-sketch_tree'  

But '/Users/zhouhancheng/编程/github_own/sketch_worktree/pubsub-sketch_tree' had been removed.

Upvotes: 37

Views: 57414

Answers (4)

What Would Be Cool
What Would Be Cool

Reputation: 6758

In my case it was because a rebase was in progress. I switched to the branch I wanted to remove and then aborted the rebase and then I was able to delete it.

git checkout {branch-to-delete}
git rebase --abort 
# or
git merge --abort

git checkout main
git branch -D {branch-to-delete}

Upvotes: 23

Dorian
Dorian

Reputation: 9085

For me the solution was to do git bisect reset

Upvotes: 10

VonC
VonC

Reputation: 1324178

I've removed its working directory

You will have an easier time with Git 2.17+ (Q2 2018), since "git worktree" has learned 'move' and 'remove' subcommands.

See commit 7f19def (04 Mar 2018) by Eric Sunshine (sunshineco).
See commit ee6763a, commit cc73385, commit 78d986b, commit c64a8d2, commit 9f792bb, commit 9c620fc (12 Feb 2018), and commit 4ddddc1 (24 Jan 2018) by Nguyễn Thái Ngọc Duy (pclouds).
(Merged by Junio C Hamano -- gitster -- in commit bd0f794, 14 Mar 2018)

worktree remove: new command

This command allows to delete a worktree. Like 'move' you cannot remove the main worktree, or one with submodules inside.

For deleting $GIT_WORK_TREE, Untracked files or any staged entries are considered precious and therefore prevent removal by default. Ignored files are not precious.


worktree remove: allow it when $GIT_WORK_TREE is already gone

"git worktree remove" basically consists of two things

  • delete $GIT_WORK_TREE
  • delete $GIT_DIR (which is $SUPER_GIT_DIR/worktrees/something)

If $GIT_WORK_TREE is already gone for some reason, we should be able to finish the job by deleting $GIT_DIR.

Upvotes: 14

torek
torek

Reputation: 488183

You are using git worktree, so the answer is in the git worktree documentation:

When you are done with a linked working tree you can simply delete it. The working tree’s administrative files in the repository (see "DETAILS" below) will eventually be removed automatically (see gc.worktreePruneExpire in git-config(1)), or you can run git worktree prune in the main or any linked working tree to clean up any stale administrative files.

(emphasis mine). Git won't let you delete the branch if it believes it is checked out in a secondary worktree. If the secondary worktree is already removed, but Git has not yet caught on to that fact, just run git worktree prune to tell Git to go check.

Upvotes: 36

Related Questions