Git worktree it a git feature which allows you to checkout a single repository into multiple locations on your filesystem. It has a few rough edges, but if you follow a few simple rules it can be make context switching much easier than git's other mechanisms, such as stashing or switching branches. My folder structure will usually look something like this:
MyRepo/
       master/ ← The original checkout, using something like git clone <repo url> master
       feature_branch_1/ ← A feature branch
       hotfix_branch_1/ ← A quick hotfix I need to make
- Create the top-level folder: mkdir MyRepo
- Checkout the repository's master branch as a normal checkout: cd MyRepo; git clone <repo url> master
- Add a branch: cd master; git worktree add -b <branch_name> ../<folder_name> HEAD
- branch_nameand- folder_nameshould likely be the same to avoid confusion (in larger projects, I would prepend- branch_namewith my username)
- Switch to that branch: cd ../my_branch
- When you need to create a new branch, make sure to create it from the branch you want to base it on (often, this is master)
- git worktree remove <path_to_worktree>from a directory containing your worktree
- (Optional) Delete the local branch with git branch -D branch_name
- (Optional) Delete the remote branch with git push <remote> :<branch_name>
- In a worktree, the .gitfolder is just a file, so scripts modifying repo settings like git hooks may fail. The git hooks in the original repository apply to its worktrees.
- You can actually checkout a worktree inside of the repository by leaving out the ../before folder name. This is not recommended.
- You can not have the same branch checked out in multiple worktrees