git,

Multiple working directories in Git

Oct 20, 2022 · 1 min read · Post a comment

Multiple working directories in Git are commonly used when working on multiple branches at once using git worktree. Other alternatives include working in the GitHub UI (which might not be the case for everyone), or cloning the repository to another directory or even another machine. This comes with downsides as well, duplication of data for instance. So, this is where git worktree comes into play.

Prerequisites

  • Git

Solution

List current Git worktrees.

git worktree list

Create a working tree from a new branch.

git worktree add api-2 origin/main -b bugfix

Create a working tree from an already existing branch.

git worktree add api-2 feature1

To remove a working tree, run:

git worktree remove api-2

If you have already rm -rf the subdirectory of the working tree, the tree will become prunable. Next logical step is to run:

git worktree prune

There’s one downside though:

  • You can’t checkout the same branch in more than one working tree, hence you’ll get the following error:
    Preparing worktree (checking out 'main')
    fatal: 'main' is already checked out at '/Users/devcoops/repos/api'
    

Conclusion

To find more neat Git commands and hacks, simply browse the Git category. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.

git