Today I Learned : Git Worktree

A git repository can support multiple working trees, allowing you to check out more than one branch at a time. With git worktree you can add a new working tree that is associated with the repository, along with additional metadata that differentiates that working tree from others in the same repository. The working tree, along with this metadata, is called a "worktree".

While working on multiple branches of a codebase I have come across multiple scenarios where sometimes I am building something and have to switch branches to fix a bug on priority and send it to production. git stash is one solution but it becomes messy if you have multiple changes stashed, maintaining node modules becomes a hassle if there are different ones on different branches, worktree makes all of this work like magic !

# Create a branch-2 dir with the branch-1 checked out
git worktree add ../branch-2 branch-1

# Then simply get to work
cd ../branch-2
git fetch && git reset --hard origin/branch-1
git checkout -b branch-2

Now I can contribute to multiple branches easily and can simultaneously test out the branches without one branch impacting the other branch at all.

blogs