Git Reference ยท Concepts
HEAD, the index and the working tree
Learn the three trees behind reset, checkout, restore and diff: HEAD, the index and the working tree, and which command moves data between them.
Almost every everyday Git command moves content between three places, often called the three trees:
- HEAD: the snapshot of the last commit on the current branch. It is read-only; only a new commit changes it.
- The index (staging area): the proposed next commit.
- The working tree: the real files on disk that you edit.
Once you know which of the three a command reads and which it writes, commands like reset, restore, checkout and diff stop being mysterious. git status is simply two comparisons: HEAD against index ("changes to be committed") and index against working tree ("changes not staged").
git diff # index -> working tree git diff --staged # HEAD -> index git diff HEAD # HEAD -> working tree git restore file # index -> working tree (discard edits) git restore --staged file # HEAD -> index (unstage) git restore --source=HEAD --staged --worktree file # HEAD -> both
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.
Syntax
There is no single command for this idea, so here is the map of who writes where.
| Command | Reads | Writes |
|---|---|---|
git add |
working tree | index |
git commit |
index | new commit, moves the branch (so HEAD) |
git restore file |
index | working tree |
git restore --staged file |
HEAD | index |
git reset --soft C |
HEAD (branch only) | |
git reset --mixed C |
C | HEAD and index |
git reset --hard C |
C | HEAD, index and working tree |
git switch branch |
branch tip | HEAD, index and working tree (refuses if it would lose edits) |
git checkout -- file |
index | working tree |
Usage notes
resetversuscheckout/switch.resetmoves the branch that HEAD points to;switchmoves HEAD itself to another branch. See Reset modes compared.- Edits you made are safe in the index too. A staged change survives
git restore file(which restores from the index), but notgit reset --hard. - Untracked files are in none of the three. Git does not know about them until they are added, which is why
reset --hardleaves them alone. - Reading a blob from each tree:
git show HEAD:path,git show :path(the index; note the empty commit part) and plaincat path. - The state of a path can differ in all three at once, which
git status --shortshows asMM(modified in index and again in the working tree). - A clean
git statusmeans all three agree for tracked files.