I was today years old when I learned you could have multiple git working trees active at the same time.
The idea is simple. Imagine you have multiple branches and you want to work on them all simultaneously. Normally you would be forced to constantly switch back and forth, shelving and stashing any changes you are yet to commit. But there’s an easier way. You just set up multiple git working trees. The following git worktree tutorial shows you how.
A git worktree tutorial
For example, imagine you initialized a git repository and created three git flow branches: fix, feature and release.
/example/git worktree add (master) $ git branch fix $ git branch feature $ git branch release
To set up multiple git working trees, you simply use the git worktree add command, with the name of the subfolder and the name of the branch specified as options. The git worktree syntax is:
git worktree add -path- -branch-
A quick git worktree tutorial in an animated GIF.
The git worktree example
/example/git worktree add (master) $ git worktree add hotfix fix $ git worktree add latest release $ git worktree add new-feature feature
The addition of these multiple working trees creates the following folder structure:
++ workspace ++ hotfix ++ latest ++ new-feature
Each of these folders is a separate branch with a separate reflog and commit history allowing for isolated development. And when work in one of these branches becomes stable, it can be merged back into the master branch using all the same commands you would normally use when only one working tree was in play.
How to delete a Git working tree?
If you’re done with one of your multiple git working trees, you can simply call the git worktree remove or prune command to delete it:
/example/git worktree add (master) $ git worktree remove hotfix
The ability to add multiple working trees with the git worktree add command is a neat trick that should eliminate the need to needlessly commit and stash changes, and help improve developer productivity when moving between multiple branches is a necessity.