Cheat sheet · No. III

Git.

Git is a content-addressed graph of commits. Almost every command that feels scary just moves a pointer: your work is rarely gone, it is usually just unreferenced.

Printable One A4 page
PLATE — GitFIG. III mainfeaturemerge HEAD → branch → commit → tree → blobone page, pinned to the wall.
The reference
DAILY
git status -sb
Short status with branch
git add -p
Stage hunks interactively
git commit -v
Commit with diff in editor
git diff --cached
What's staged
git log --oneline -20
Recent commits
git log --graph --oneline --all
Branch graph
UNDO
git restore <file>
Discard unstaged change
git restore --staged <file>
Unstage
git commit --amend
Edit last commit
git reset HEAD~1
Undo commit, keep changes
git reset --hard HEAD~1
Undo and discard
git revert <sha>
Inverse commit (safe for shared history)
BRANCH & MERGE
git switch -c <name>
Create + switch
git switch -
Previous branch
git merge --no-ff <b>
Merge with merge commit
git rebase <b>
Replay onto base
git rebase -i HEAD~5
Interactive rewrite
git cherry-pick <sha>
Pull one commit over
RECOVER
git reflog
Log of HEAD movements (90 days)
git reset --hard HEAD@{2}
Jump to reflog entry
git stash
Save unfinished work
git stash pop
Bring it back
git fsck --lost-found
Find dangling commits
REMOTE
git fetch --prune
Update tracking, drop deleted
git pull --rebase
Pull without merge commit
git push -u origin <b>
Push and set upstream
git push --force-with-lease
Safe force-push
SEARCH
git log -S "text"
Commits that add/remove "text"
git log -G "regex"
Commits matching regex in diff
git blame <file>
Per-line authorship
git bisect start
Binary-search for the breaking commit
Field notes
reflog is the safety net

Even after a hard reset or a botched rebase, HEAD@{n} remembers where you were for about 90 days. You can almost always get back.

revert vs reset

revert adds an inverse commit, safe on shared branches. reset rewrites history, only on branches no one else has pulled.

Force safely

Use --force-with-lease, never plain --force: it refuses to clobber commits you have not seen, so you never overwrite a teammate.

Commit small, tidy later

Messy local history is free to clean up with rebase -i before you push. Pushed history is not, so commit often, polish before sharing.

Tip: hit ⌘P / Ctrl-P to save this single page as a PDF or print it for the wall.

Found this useful?

Published