World map

 

BM: Baca dalam Bahasa Melayu

World 10: Deep Git

git worktree

You will learn: how to work on two branches at once, in two folders, with one repo.

The problem

You are halfway through a big change. Then a bug report: fix main right now! Which way leaves your half-done work untouched?

Pick one answer.

Watch

git worktree add makes ../diary-fix on a new branch fix. git worktree list shows two folders: diary on main and diary-fix on fix. Terminal output: $ git worktree add ../diary-fix -b fix Preparing worktree (new branch 'fix') HEAD is now at e0b2bc1 Add day 2 $ git worktree list /home/you/diary e0b2bc1 [main] /home/you/diary-fix e0b2bc1 [fix]

git worktree add makes a second working folder, on its own branch. Same repo, same history. Each folder is a worktree: An extra working folder for the same repo, on its own branch..

Try it

Make a worktree at ../diary-fix on a new branch called fix.

04b414ee0b2bc1

Predict

You commit a fix inside diary-fix. Then you go back to diary. Can you see that commit there?

Pick one answer.

Watch

After git worktree remove, the list shows only diary. git branch still lists fix and main. Terminal output: $ git worktree add ../diary-fix -b fix Preparing worktree (new branch 'fix') HEAD is now at e0b2bc1 Add day 2 $ git worktree remove ../diary-fix $ git worktree list /home/you/diary e0b2bc1 [main] $ git branch fix * main

Done? git worktree remove deletes the extra folder. The branch and its commits stay safe.

Check

Put the bug-fix trip in order.

First step at the top. Put these in order. Use the arrows, or drag.

  • cd ../diary
  • Fix the bug and commit
  • git worktree add ../diary-fix -b fix
  • git worktree remove ../diary-fix
  • cd ../diary-fix

You did it!

You can now work on two branches at once, in two folders.

Go deeper (optional)

A branch can be checked out in just one worktree at once. Git refuses a second one. git worktree remove refuses if the folder has changes; --force drops them. Deleted a worktree folder by hand? git worktree prune cleans up Git’s notes about it.