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’.

BASH
git clone git@github.com: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.

BASH
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.

DOCKERFILE
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.

BASH
git switch -c dev
git push origin dev

You can remove worktree

BASH
git worktree remove test

and remove completely from ref.

EBNF
git worktree prune

That’s all you needed. More git worktree commands

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

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

Download source code