News Stay informed about the latest enterprise technology news and product updates.

Use this git worktree add example and never switch branches again

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-

git worktree tutorial

A quick git worktree tutorial in an animated GIF.

The 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 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

git worktree example

A git worktree remove command example.

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.

 

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.

-ADS BY GOOGLE

SearchAppArchitecture

SearchSoftwareQuality

SearchCloudComputing

SearchSecurity

SearchAWS

Close