Updated: 01.04.2022

Normally I created a new branch when I intent to do some changes to the master branch. But the problem is I have to stash changes when switching back and forth. To avoid this create worktree for the branches you want to work seperately. Basically it creates a new folder and work independently.

Create new worktree

To start worktree with newfix from master branch. You can create newfix branch first then worktree or directly to create worktree with newfix branch

  git branch fix
  git worktree add ./path/newfix fix

  # direct from origin/master
  git worktree add -b fix ./path/newfix origin/master

This will create fix branch and newfix folder at ./path/newfix. The example above uses origin/master which is the default and can be ignored. If you select different branch then you can specify origin/fix. To work with the new worktree newfix branch then you just need to change folder

  cd ./path/newfix

  # Check you are in fix branch
  git status

Copy branch to a worktree

To copy en existing branch to a worktree:

git worktree add --track -b <branch> <path> <remote>/<branch>

# example
git worktree add --track -b user ../worktree/orgdata origin/user

Delete worktree

To list down all the workrees you can use git worktree list. Deleting a worktree can be done by deleting the folder directly and run git worktree prune to delete it from the list. If you have error because your branch already checked out then delete .git/worktrees/newfix. See https://www.saltycrane.com/blog/2017/05/git-worktree-notes/

  rm -rf path/newfix
  git worktree prune
  git branch -d fix
comments powered by Disqus