Use git worktree add and never switch branches again
Git Worktree Add Example
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 want to work on them all simultaneously. Normally you’d be forced to constantly switch back and forth, shelving and stashing any changes you would commit. But there’s an easier way. Just set up multiple git working trees. The following git worktree tutorial shows you how to do just that.
A git worktree add tutorial
For example, imagine that 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
A developer can set up multiple git working trees with 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 git worktree example
For example, with git cloned or initialized in a folder named \workspace, you could add subfolders for each of the active branches with the following ‘git worktree add’ commands:
/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, which allows 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 the multiple git working trees, 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. It will help improve developer productivity when it’s necessary that they move between multiple branches during development.