Use Git Worktree to Reduce Burden of Context Switching

Introduction

Recently, whether using AI Vibe Coding or switching git branches at work, using git stash🔗 feels inconvenient. Although I’ve heard that git worktree🔗 can solve this problem, I was too lazy to learn it at first. Now I finally took the time to seriously learn how to use git worktree to quickly switch between projects.

Problem

Suppose you’re writing some code on branch A, but suddenly need to switch to branch B to fix an issue. Usually, I would run git stash -m 'describing what I wrote' and then check out branch B to work. After finishing, I’d check back to A and git stash apply to restore the stash content. Most of the time, this pattern works fine.

But I found that sometimes it becomes cumbersome to “open different branches for cross-development” simultaneously. Occasionally, I would even go to the GitHub/GitLab webpage to browse files from other branches (refer to: Share a tip I often use when previewing GitHub projects) or clone multiple copies of the same project locally.

git worktree

First, check the existing worktrees with: git worktree list, and naturally, there won’t be anything.

Terminal window
/home/riceball/Desktop/git-projects/riceball-obsidian 628b009 [main]

Add a new worktree with: git worktree add file_location target_branch. A new-post folder has been added in the previous directory, containing content from the feat-new-post branch.

Terminal window
riceball@joe-pc:~/Desktop/git-projects/riceball-obsidian$ git worktree add ../new-post feat-new-post
Preparing worktree (checking out 'feat-new-post')

They share the same .git records, making it lighter compared to simply doing a git clone. You can also move an existing worktree:

Terminal window
git worktree move ../new-post ./foo

Finally, delete unwanted worktrees:

Terminal window
git worktree remove ./foo

Summary

You can think of git worktree as a way to clone specific branches of a repository without actually retrieving the entire history. It is more flexible than stash and light weight enough. It can be used alongside stash to create clean workspace separations, reducing the burden of context switching.

Further Reading