Skip to main content
Code and think

Worktree

When you work on different features simultaneously in git, worktrees are very useful feature. You can manage multiple working trees attached to the same repository. Imagine you are working on a big feature, that will take some time. You can create a separate worktree for it. Now, in case you need to urgently fix a bug while working on a big feature, you can do it in a main worktree without disturbing the process of developing a big feature.

When you start working on a big feature, add a new worktree:

git worktree add -b feature/my-feature ../my-feature master

In case you are happy with the branch name being the same as the folder you can skip it, and git will automatically create a new branch for you.

git worktree add ../my-feature

The command above will create a new folder (parallel to the current clone) and a branch named my-feature. The branch will be created from the current.

git worktree add ../my-feature my-existing-branch

This will create a new folder in parallel with your clone named my-feature and checked out branch an existing branch my-existing-branch. The branch must exist prior adding work tree in such way. Path (../my-feature in example above) is the only mandatory parameter. The name after the last / is also the name of the worktree. You need the name for e.g. removing the worktree.

Once you merge the functionality to master or you finish with it some other way, you can remove the worktree:

git remove worktree ../my-feature

or just by name:

git remove worktree my-feature

At any time, you can check what work trees exist with:

git worktree list

For additional commands review the git documentation.

Worktree vs multiple clones #

I tested on a large clone which takes over 7GB of disk space. Creating a new clone would be additional 7GB. By adding a new work tree I used less than 1GB, so a huge saving of disk space. Another example was repo that takes 2GB, whereas worktree takes 200MB of disk space. The downside can be that in case you damage your main clone, the work trees will also be affected.

Reference