gitgit-worktree

How to switch branches between two separate worktrees in Git?


I added a linked working tree for "develop" branch. So my worktrees are like this:

- "project" worktree -> master branch
- "project_develop" worktree -> develop branch

In this condition, what I want to do is to checkout master branch on "project_develop" worktree. But as I know, it is impossible to checkout same branch on separate worktrees. The only way I could think of is to add a new temporary branch.

I would appreciate it if someone show me another way.
Thanks!


Solution

  • The easiest way is, on the master worktree

    git checkout --detach
    

    There are numerous other ways; the point is, since you don't have another branch to checkout to this worktree, you want to force it into detached HEAD state. It can still have the same code checked out; it just can't think it's "on" the master branch (since there would be problems with updating the worktrees on commit).

    Once that's done, on the 2nd worktree you can git checkout master, and then if you want you could even go back to the first worktree and git checkout develop to swap the branches entirely. Or just wait until you're ready to check develop back to the 2nd worktree, and afterward check master out on the 1st tree again...