On using git worktrees

You know that thing that you know you need to learn, that once you learn you’ll regret not having learned earlier?

That was git worktrees for me.

This is not intended to convince anyone to join the wagon.

I am writing this to serve as a reminder to myself and to have an easy place to go back to when I need to refresh on the basics. And here are the basics:

What it is:

  1. Git worktrees allow you to work on multiple branches on the same repository at the same time.
  2. In essence you create a new directory and navigate to it when you need to work on the other branch.
  3. It is useful when you don’t want to stash or commit.
  4. It uses the git smarts to avoid copying the whole thing and to keep the reference to the right repo.

How to do it (basic commands):

I tend to create the worktree directories at the same level as the directory where I keep the code (main), hence the code below uses a ../ to go one level up. Here’s the basic commands:

  • Create a work tree: git wortree add -b branch-name ../folder-name
  • Remove a work tree: git worktree remove ../folder-name
  • Prune trees: git worktree prune

That is it really.