Git WorkTree | Concurrently managing multiple branches without affecting the changes on individual branches

Amitchaudhary
Bajra Technologies Blog
3 min readMar 26, 2024

--

When you are working on a feature with multiple changes that are not committed or are not ready to be committed yet and if you encounter a bug or have to work on another feature of a higher priority, then you probably work on them, save all your previous changes, and use the most-known and followed feature - Git-Stash.

Git WorkTree

Git also provides another feature called Git WorkTree to handle these situations. In this blog, I will give you a rundown of how to use this unique feature.

Git WorkTree

In simple words, Git Worktree allows you to create multiple branches at once by cloning the same repository.

Here’s what Git’s official document says:

Manage multiple working trees attached to the same repository.

Why Git WorkTree?

Whether you are working on a new feature, bug fix, or any code refactoring, you can switch to another task without making any modifications to your current work directory by switching to a separate branch.

How to create a WorkTree?

git worktree add command creates a worktree along with a branch that is named from the path. Here, the branch name will be worktree_name. You can do so as follows:

git worktree add <PATH>
# Create directory and branch with the same name.
git worktree add ../worktree_name
Git worktree with the same branch as the directory

When you want a specific branch name, use the -b flag:

git worktree add -b branch_name ../worktree_name
Git worktree with specific branch name

List the WorkTree

To list the worktree that you have created, use the following command:

git worktree list
Git worktree list

Switch to a WorkTree

Navigate to the path where you have added the worktree. You can get the path from thegit worktreelist. I know switching worktrees is not as easy as adding aworktree. But, the Git WorkTree Switcher tool makes it a lot simpler.

Pulling updates on a WorkTree

To pull updates on a worktree, just do a git fetch or git pull. Either works fine and updates a worktree but you have to be careful of any merge conflicts. If you update one worktree, all the updates are reflected on the other open worktrees instantly because you are working with the same underlying data across all of your worktrees.

Removing a WorkTree

Once you have finished working on a tree, you can remove the worktree. To do so, use the command:

git worktree remove worktree-name
Available git worktrees
Removed worktree create_todo

Example

Conclusion

Git WorkTree is a compelling feature provided by Git. It comes in handy when working on multiple fixes and features without affecting the changes of one branch on another branch. Again, it is going to depend on your actual circumstances in terms of when to use Git WorkTree over Git Stash, but if you ever need an option, I hope this article is useful for you.

Resources

--

--