Git Moving a worktree


Example

Currently (as of version 2.11.0) there is no built-in functionality to move an already existing worktree. This is listed as an official bug (see https://git-scm.com/docs/git-worktree#_bugs).

To get around this limitation it is possible to perform manual operations directly in the .git reference files.

In this example, the main copy of the repo is living at /home/user/project-main and the secondary worktree is located at /home/user/project-1 and we want to move it to /home/user/project-2.

Don't perform any git command in between these steps, otherwise the garbage collector might be triggered and the references to the secondary tree can be lost. Perform these steps from the start until the end without interruption:

  1. Change the worktree's .git file to point to the new location inside the main tree. The file /home/user/project-1/.git should now contain the following:

    gitdir: /home/user/project-main/.git/worktrees/project-2
    
  2. Rename the worktree inside the .git directory of the main project by moving the worktree's directory that exists in there:

    $ mv /home/user/project-main/.git/worktrees/project-1 /home/user/project-main/.git/worktrees/project-2
    
  3. Change the reference inside /home/user/project-main/.git/worktrees/project-2/gitdir to point to the new location. In this example, the file would have the following contents:

    /home/user/project-2/.git
    
  4. Finally, move your worktree to the new location:

    $ mv /home/user/project-1 /home/user/project-2
    

If you have done everything correctly, listing the existing worktrees should refer to the new location:

$ git worktree list
/home/user/project-main  23f78ad [master]
/home/user/project-2     78ac3f3 [branch-name]

It should now also be safe to run git worktree prune.