Working on multiple branches simultaneously in a single repository

In a perfect world, every developer should be focused on a single task or story, not having to switch between different contexts. Let’s face it, that is rarely the case nowadays. Fortunately, git has the perfect tool in its arsenal, allowing developers to work on multiple branches simultaneously without traversing back and forth. The instrument in question is git worktree.

Requirements:

To start a worktree you need an initialized repository, optionally with multiple branches.

For example, let’s consider a repository with three branches. list-users-API, a feature branch that happens to be the current active branch, the main branch, and user-unable-to-edit-content, an additional bug branch. A possible scenario is that the bug branch didn’t pass code review and further changes are required. There are a couple of ways we could proceed from here:

  1. Stash all of our progress and switch to the bug branch to apply the necessary changes.
  2. Clone the repository in a different folder and solve the problem without having to stash, but invest a considerate amount of time in the process.
  3. The third and final approach is using git worktree, retaining our current progress on the feature branch, and avoiding switching entirely.

Let’s explore the latter possibility.

Implementation:

To get started, use the following command to initialize a worktree:

$ git worktree add <path> [<commit-ish>]

The <path> specifies the name of the directory and [<commit-ish>] the branch that is checked out into the worktree. For the sake of simplicity, we are going to create it with the name of the branch (e.g. git worktree add user-unable-to-edit-content). When the worktree has been initialized, you should see the following message:

If you use git branch now, you are going to see a + symbol, prefixing the branch name. To start using the worktree, all we have to do is open the new directory inside the repository with the IDE of our choosing. Now we can push changes to the bug branch alongside developing the new feature. Once we are finished with the changes, we can remove the worktree using:

$ git worktree remove <worktree>

Conclusion:

Git worktree is a handy instrument, that boosts versatility and saves a substantial amount of time. It allows working on two or more branches without having to stash or commit unfinished code. I hope this article has been of help & will boost your productivity. Please provide any feedback you deem worth sharing in the comments!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store