Git Cheatsheet
Top commands.
Reading history
git log --oneline -20: last 20 commits, one line each.
git log --all --graph --oneline --decorate: graph view across all branches. Useful for understanding merge history.
git log --grep='fix bug' --since='2 weeks ago': filtered history. Search by message and time.
Understanding code
git blame file.py: who changed each line, when, why (commit message). Often the first step in debugging legacy code.
git log -p -- file.py: full diff history of a file. Track how it evolved.
git show HEAD~3: shows commit three back from HEAD with full diff.
Branch operations
git switch -c feature/x: create and switch to new branch. Modern alternative to git checkout -b.
git switch main: switches branches without creating.
git branch -d old-branch: deletes merged branch. -D for force delete.
Rewriting history
git rebase -i HEAD~5: interactive rebase of last 5 commits. Squash, reword, drop, reorder.
git rebase main: replay current branch onto latest main. Linear history.
git pull --rebase: pull with rebase instead of merge. Cleaner history for shared branches.
Recovery
git reflog: shows everything you've done locally. Recover from any mistake within reflog window.
git reset --hard ORIG_HEAD: reverts last operation. ORIG_HEAD is what HEAD was before the last move.
git fsck --lost-found: finds dangling objects after deletions. Last-resort recovery.