Git·30 questions

What is git worktree and how to work with multiple branches simultaneously?

Answer

Usually when working with Git, you have a single working directory, and to switch between branches you constantly have to use the `checkout` or `switch` command, which can be inconvenient if the current code is unfinished or requires a long build. The `git worktree` command solves this problem by allowing you to create several independent working catalogs associated with the same local repository.

Each new working tree functions as a separate folder on your computer, in which a completely different branch can be opened. At the same time, they all reference a single `.git` database, which saves disk space and avoids the exhausting process of cloning the repository anew. You can simultaneously compile a project in one folder on the master branch and make urgent fixes in another folder on a feature branch.

To create a new workspace, the `git worktree add` command is used, specifying the path to the new folder and the name of the branch you want to open there. For example, the command `git worktree add ../hotfix-folder hotfix` will create a parallel directory one level up and switch it to the hotfix branch. Now you can work independently in both folders.

After finishing work with the additional catalog, it can be safely removed using the `git worktree remove` command with the path to the folder. This will clean up temporary files and remove the entry from Git's system list of working trees without affecting the commits and changes that were successfully committed in the repository.

Was this answer helpful?

More questions in this topic

Related questions from other topics