Make use of multiple working trees in git

I thought I would start a blog post series about some lesser-known git features. So here we go! With no further ado let’s kick things off with git worktree.

Normally if you clone a repository you are switching branches in your working directory. But let’s imagine you don’t want to or are not able to switch branches because of some local changes. Of course, you can stash your changes and reapply them after you switched back but maybe you would have to deal with conflicts and you are not in the mood right now.

Thanks to git you have another option. You can add another working tree pointing to the same git repository.

$ git worktree add -b fix/1337 ../my-project-fix-1337

With this command, you will create another directory besides your project directory holding another working copy with a new branch called fix/1337.
To get a list of your currently active working trees run the following command.

$ git worktree list
/home/sf/repos/my-project            d7f49ad [master]
/home/sf/repos/my-project-fix-1337   d7f49ad [fix-1337]

You can now switch to the new directory and work in there just like you are used to. If you are done you can delete the new directory and clean up the working tree reference.

$ rm -rf ../my-project-fix-1337
$ git worktree prune

Git will cleanup unavailable working trees during garbage collection automatically. If you have additional working trees on network drives that aren’t available 100% of the time you can force git to keep them by locking them with.

$ git worktree lock ../my-project-fix-1337

Other commands for git worktree are unlock and remove. Multiple work trees can be extremely handy to checkout branches for local code review without interfering with your development.

Maybe give multiple working trees a try and see if you find it useful. See you at the next article of the “lesser-known git features” series 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *