Git worktree example

Git corktree example with video

Git worktree is great a way to separate your code without having to create a new branch when you are not yet ready to commit.

I have created a new repo in GitHub and cloned in a dir ‘worktree-example’.

git clone [email protected]:sminrana/git-worktree-example.git

Open the dir with code . command and update the readme.md file. Now we can push it to main branch.

git add README.md 
git commit -m "message"
git push origin main

It’s time to create our first worktree. We will put our worktree one dir up from our current dir where our main branch is. The documentation says -d flag with single hyphen but two hypen worked for me.

git worktree add --d ../test 

Now open test folder and open it in code . and make some changes in readme file then commit. Since worktree is detached HEAD you can’t commit to anywhere, for this we have create a new branch from here, run following command.

git switch -c dev
git push origin dev

You can remove worktree

git worktree remove test

and remove completely from ref.

git worktree prune

That’s all you needed. More git worktree commands

git worktree add --d ../hotfix 
git worktree remove hotfix
git worktree prune

Throwaway working tree
git worktree add --d <path>

Download source code

Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Leave a comment