Have you ever been in the middle of an important project when you had to switch to a different branch to fix something? Obviously, you had.
When we are making progress on one branch but need to switch to another, we usually commit or stash our modifications so that we may return to them later. Is it feasible, though, to just move to a different branch, without going through the procedures outlined above? Absolutely, that’s the case.
Both the video up top and the text below will walk you through the processes required to manage many branches simultaneously.
Git Worktree allows us to take control of various working trees connected to the same repository.
You can check out numerous branches at once by using a git repository that now supports multiple working trees when created with git worktree.
– So, how to?
# git worktree add will create a new worktree with a name of our choice git worktree add name_of_our_branch
Once you’ve executed the mentioned command, you should see a new folder in your project’s directory matching the name we gave our workbranch. *See the screenshot below)
With this new folder in hand, we can launch an integrated development environment (IDE) window (I’ll be using Visual Studio Code, but any IDE would suit) and navigate into the worktree folder.
Once you navigated to the folder, you can start working on the fix or anything that interrupted your work on the ‘important branch’. Commit your changes and push them to the main branch of your project and close the IDE.
Now, go back to your branch where you created the worktree and run the following command, to see a list of our worktrees.
# the following command lists all worktrees related to our repository git worktree list
After running the
list command you should see something like this in your terminal.
Now you can remove your worktree that we previously created by running the following command:
#Removes worktree - git worktree remove name_of_our_worktree
After running the command, we can see that the folder has been removed from our project. Also we can run
git worktree list again to be sure that it has been removed.
By following the displayed instructions, we were able to add, list, and delete worktrees from our project. While you’re free to put your worktree wherever you choose, I find it most convenient to add it to the root folder of the project, where I’ll have access to all of the necessary node modules without having to reinstall them.
I hope the article was helpful.
Feel free to follow me for more content like this!
Leave a Reply