Skip to content

Instantly share code, notes, and snippets.

@GeorgeLyon
Last active September 25, 2024 15:08
Show Gist options
  • Save GeorgeLyon/ff5a42cb24c1de09e4139266a7689543 to your computer and use it in GitHub Desktop.
Save GeorgeLyon/ff5a42cb24c1de09e4139266a7689543 to your computer and use it in GitHub Desktop.
Git Worktree Overview

git worktree

What is it?

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

Creating Worktrees

  1. Create the top-level folder: mkdir MyRepo
  2. Checkout the repository's master branch as a normal checkout: cd MyRepo; git clone <repo url> master
  3. Add a branch: cd master; git worktree add -b <branch_name> ../<folder_name> HEAD
  • branch_name and folder_name should likely be the same to avoid confusion (in larger projects, I would prepend branch_name with my username)
  1. Switch to that branch: cd ../my_branch
  2. 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)

Removing Worktrees

  1. git worktree remove <path_to_worktree> from a directory containing your worktree
  2. (Optional) Delete the local branch with git branch -D branch_name
  3. (Optional) Delete the remote branch with git push <remote> :<branch_name>

Gotchas

  • In a worktree, the .git folder 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
@rahulkashyap-phy
Copy link

I have a question. In a gitrepo, I have two remotes (gitHub, gitlab). I created a new branch locally (git worktree add -b newlocalbranch ./newlocalbranch) and wanted to push that branch to only one of the remotes. How can I do that?
Thanks in advance.

@GeorgeLyon
Copy link
Author

This would work the same way that it would without worktrees, you would need to specify the remote manually when pushing.

@rahulkashyap-phy
Copy link

yes, I tried and it worked. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment