Have you ever been busy working on a branch but needed to push something to another branch without disrupting work on your current branch? Enter the worktree feature! It was introduced in Git 2.5 and is very handy when working on multiple branches simultaneously, without disrupting your work on the other branch. It got me very confused at first but it’s quite simple.

What Git does is it creates a new folder with a specified branch checked out. There’s nothing more to it other than that. Of course under the hood Git creates a new .git folder for it internal workings but we won’t be going into that.

Let’s say I have two branches, master and feature/a. I’ve got my feature/a branch checked out and working hard to finish feature A. When I type git status I would get something like this (see below).

Now I want to go back to master and push some changes. So if I checkout master I get something like this:

This is because master doesn’t have these files and because Git is tracking them, they would be overwritten. That’s not good. So I have to either commit the changes or stash them so I can be able to switch branches.

But what if I’m not ready to commit just yet? I could stash the changes, go to master, commit and push my changes, go back to my feature branch, pop the stashed changes and then continue working on my changes. That would work well in this particular case, but let’s face it, it’s too much hassle and is not very productive if you wan’t to continue working on those branches simultaneously.

So let’s use the awesome worktree feature! Begin by adding a new worktree for the master branch.

NOTE: It’s highly recommended to add worktrees at the same level as the repository, to avoid the possibility of accidentally committing your worktree into your original repository. You could also create a folder inside your repository named worktrees, add it to your .gitignore file and then put your worktrees in there. I’m not doing this below just to demonstrate the changes and the added worktree folder, but YOU SHOULD.

So the syntax for adding the worktree is the following:

Something like this:

Now if you type git status you should see something like this:

Take a look at that new master-branch folder. This is a new Git repository with the master branch checked out. Take a look at the following GIF showing when I go in and out of that folder. It’s like a completely new environment.

You can add as many worktree folders as you want.

If you want to delete them, just delete the folder and type: git worktree prune

You’re done. Simple as that.