Search code examples
gitgit-checkoutgit-worktree

May I force git to change directory instead of fatal error while checking out branch from different worktree?


I have few work trees:

$ git worktree list
/home/kes/work/projects/video/app     7509c7f [dev]
/home/kes/work/projects/video/second  c12cdf9 [newbr]

I want to be switched to different directory, when I do git checkout newbr from dev branch (worktree), instead of get error:

$ git checkout newbr
fatal: 'newbr' is already checked out at '/home/kes/work/projects/video/second'

Currently I do:

cd /home/kes/work/projects/video/second

Is there an option to do this automatically?


Solution

  • No, this isn't possible. The current working directory is an attribute of a process (in this case, your shell) and processes that are invoked from it (like Git) cannot change their parent's working directory. Allowing that to happen would break a lot of software.

    You can create an alias or function in your shell, say gco, that will look up to see if there's a worktree for your repository, and if so, switch to it, and if not, check out that branch. Since that operation happens entirely within your shell, it's possible to change the working directory for your shell.