Git Cheatsheet
Top commands.
Reading history
git log is the entry point to every history investigation. The right flags turn it into a precision tool.
- git log --oneline -20: Per-repo the recent-commit summary. Last 20 commits, one line each.
- git log --all --graph --oneline --decorate: Per-repo the cross-branch graph. Useful for understanding merge history.
- git log --grep='fix bug' --since='2 weeks ago': Per-search the filtered history. Search by message and time.
- git log -S'pattern' -- file.py: Per-pattern the pickaxe search. The discipline finds when a string entered or left.
Understanding code
blame, log -p, show are the daily archaeology surface. Each answers a different "why is this here" question.
- git blame file.py: Per-line the author and commit. Often the first step in debugging legacy code.
- git log -p -- file.py: Per-file the full diff history. Track how it evolved.
- git show HEAD~3: Per-commit the full diff three back from HEAD.
- git blame -L 10,20 file.py: Per-range the focused blame. The discipline supports investigation of a specific block.
Branch operations
switch and branch are the modern primitives. Use switch over checkout for new branch operations.
- git switch -c feature/x: Per-feature the new branch. Modern alternative to git checkout -b.
- git switch main: Per-context the branch change. Switches branches without creating.
- git branch -d old-branch: Per-cleanup the merged-branch deletion. -D for force delete.
- git branch --merged main: Per-cleanup the already-merged list. The discipline supports periodic pruning.
Rewriting history
Rebase is its own discipline. Interactive, onto-main, pull-rebase each map to a specific cleanup.
- git rebase -i HEAD~5: Per-cleanup the interactive rebase of last 5 commits. Squash, reword, drop, reorder.
- git rebase main: Per-feature the replay onto latest main. Linear history.
- git pull --rebase: Per-pull the rebase instead of merge. Cleaner history for shared branches.
- git rebase --autosquash: Per-cleanup the fixup-aware rebase. The discipline supports fixup-marked commits.
Recovery
Recovery is the last-resort discipline. reflog, reset, fsck.
- git reflog: Per-repo the local-action log. Recover from any mistake within reflog window.
- git reset --hard ORIG_HEAD: Per-incident the revert-last-operation. ORIG_HEAD is what HEAD was before the last move.
- git fsck --lost-found: Per-repo the dangling-object finder. Last-resort recovery.
- git stash list / pop: Per-context the stashed-change recovery. The discipline supports interrupt-driven workflows.