Search code examples
gitgit-worktree

Why does git worktree add create a branch, and can I delete it?


I used git worktree add to create a new worktree. I noticed that is has created a new branch in the repo with the same name as the worktree. What is this branch for?

I have checked out an other, pre-existing branch in the second worktree. Am I free to delete the branch that git worktree add created?


Solution

  • The branch is necessary because you cannot have the same branch checked out in different worktrees at the same time.

    So if you do not specify a branch when adding the worktree, then git will add one automatically, based on your current branch and with the name of the worktree directory.

    You may ask, why cannot I have the same branch checkout out twice? Think of what will happen to worktree A when you commit to B, if they both share the branch... the worktree A will see the commit in B as a local difference, but in reverse! just as if you did git reset --soft HEAD^... That would be quite dangerous.

    BTW, that is the same reason why you cannot push to a branch of a non-bare repository that is checked out.

    About your last question: can you delete the branch? Of course, that branch is in no way special. You can delete it as long as it is not checked out anywhere.