billben.net


Git Worktrees

Probably the most underrated feature of git!

Have you ever been working on a branch and suddenly needed to work on something else in the same repo? How do you handle the context switch with a dirty working tree? Do you just commit dirty files and then create a new branch? Do you git stash everything and come back later?

NO, use git worktrees! Worktrees allow you to have 2 separate working trees of the same code base.

Below is a quick cheatsheet for using them.

I keep all my worktrees in ~/worktrees/ and all my repos in ~/repos/.

🆕 Creating a worktree

Change directory into the repo you want to work out of and run the following to add a worktree, create a new branch and place the worktree in the selected path. Optionally, pick a branch or commit to base the worktree on.

git worktree add -b [new-branch-name] [path/to/worktree] [commit/branch (optional)]

📋 Listing worktrees

List out what worktrees exist:

git worktree list
~/repos/service_name                      0000000 [master]
~/worktrees/service_name__branch_name     0000001 [feat/new_feature_one]

If you list your branches you can see which ones are worktrees (denoted by the +):

git branch
  feat/new_feature_one
+ feat/new_feature_two
* master

Cleaning up

Once you’ve merged your branch, make sure you clean up after yourself:

git worktree remove [path to worktree]

😛 Gotchas

Tags: Git, Cheatsheet