DEV Community

Philip Perry
Philip Perry

Posted on

Why use git worktree?

git worktree is a command that I came across the first time today while browsing the git documentation. The example section explains a possible use case pretty well:


From https://git-scm.com/docs/git-worktree:

You are in the middle of a refactoring session and your boss comes in and demands that you fix something immediately. You might typically use git-stash to store your changes away temporarily, however, your working tree is in such a state of disarray (with new, moved, and removed files, and other bits and pieces strewn around) that you don’t want to risk disturbing any of it. Instead, you create a temporary linked worktree to make the emergency fix, remove it when done, and then resume your earlier refactoring session.

$ git worktree add -b emergency-fix ../temp master
$ pushd ../temp
# ... hack hack hack ...
$ git commit -a -m 'emergency fix for boss'
$ popd
$ git worktree remove ../temp
Enter fullscreen mode Exit fullscreen mode

While I'm not sure if the above scenario is something where I would use it, I can see it as a useful feature for experimenting. For example, I might have a half working solution that I could stash, but if I want to switch between one approach and another idea that I have, then I think using work trees would work much better (saves me from having to keep committing code that I'm not sure will work). What do you think? Have you used git worktree?

Top comments (0)