Today I learned about a game-changer for my Git workflow: Git Worktree.
If you've ever been in the middle of a complex feature and suddenly had to drop everything to fix a critical bug on another branch, you probably reached for git stash. While stashing works, it can be a hassle to manage multiple stashes and keep track of where you left off.
Here is how git worktree allows you to work on multiple branches simultaneously without touching git stash.
The Problem with the "Stash" Workflow
Usually, when a hotfix comes in, we do this:
-
git stash(Save current changes) git checkout maingit checkout -b hotfix-branch- Fix the bug, commit, and push.
git checkout original-branch-
git stash pop(Try to remember what we were doing)
This context switching is slow and can lead to merge conflicts or lost work if you have a messy stash history.
The Solution: Git Worktree
Instead of switching branches in your current directory, git worktree lets you create a separate directory for a specific branch. This allows you to open both branches in different windows of your IDE and work on them at the exact same time.
1. Adding a Worktree
To create a new folder in your parent directory for a hotfix, run:
git worktree add ../hotfix-bug -b hotfix-bug main
What this does:
- Creates a new folder named
hotfix-bugone level up from your current folder. - Creates a new branch called
hotfix-bugbased on main. - Checks out that branch into that new folder.
Now you can simply open a new VS Code window (or your preferred editor) in that ../hotfix-bug folder and fix the bug while your main project remains exactly as you left it.
2. Committing and Pushing
In the new folder, you can follow your usual flow:
git add .
git commit -m "Fixed the critical bug"
git push origin hotfix-bug
- Cleaning Up Once the bug fix is merged and you no longer need the parallel folder, it’s important to keep your worktree clean. Move back to your main project directory and run:
cd ../main
git worktree remove ../hotfix-bug
This deletes the temporary folder and unregisters it from Git, leaving your environment tidy.
Conclusion
git worktree is perfect for those "drop everything and fix this" moments. It keeps your main workspace clean and prevents the "stash-and-dash" headaches.
References
Top comments (0)