How to work in multiple git branches simultaneously
Git worktree is the most underrated feature that helps you to work on multiple branches
Hey there! I’m Srebalaji. You are receiving this email because you have subscribed to level up your game in Git.
If you are working on a project for a while, you know you will switch between multiple branches for various reasons.
For example, you might want to switch to another branch to hotfix a prod bug. Or there may be some long-running tests you may want to run in one particular branch or other reasons to switch to other branches frequently.
Git worktree is one of the underrated features of Git that helps you to create a copy of the working repo so that you can work on it too.
Worktree unlike cloning is a soft copy of the repo so that it is lightweight and fast.
git worktree add <path> <branch_name> Example git worktree ~/workspace/feature feature
The above command will create a copy of the repo in the mentioned directory with the specified branch name.
Now you got two copies of the repo in your local. So you can work on two branches simultaneously.
One small catch is that you can’t have the same branches checked out in different worktrees. So if you have checked out one branch in one worktree, then the same branch can’t be checked out in another different worktree.
Another catch is worktrees sync up with each other. So if you have made any changes in one worktree it will automatically be synced in the other.
git worktree list
In the above image, you can see the list of worktrees of the repo. The first worktree is the default worktree which will always point to the current branch you are working on.
git worktree remove <worktree-name> Example git worktree remove feature/git-squash
I hope the above command is straight-forward.
How to use worktrees effectively
As I said earlier, worktrees are one of the underrated features of Git. But if used properly it can increase your productivity and avoid some repeatable tasks.
For example, in one of my git workflows, I used to have two worktrees checked out always.
One is from the master so that if some prod bugs come in, I can go to that directory, fix it and raise a PR.
Another one is from the develop branch where I checkout to create features.
And the last one is whenever I see an epic story, I will create a worktree for that. Because I know I’m gonna spend a lot of time on it and I will also be switching branches frequently.
To conclude, identify workflows that you can move to worktrees which will make things easier in long run.
That’s it for today :)
See you next week :) :)