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

This git worktree add example lets you 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 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-

git worktree tutorial

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

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. It will help improve developer productivity when it’s necessary that they move between multiple branches during development.


 

 

 

 

Join the conversation

1 comment

Send me notifications when other members comment.

Please create a username to comment.

We'll see if Apple computers get attacked heavily, how long it will take before Apple admits the problem exists and then does something about it.
Cancel

SearchAppArchitecture

SearchSoftwareQuality

SearchCloudComputing

SearchSecurity

SearchAWS

Close