Git Advanced Cheat Sheet

Advanced Git techniques — reflog recovery, bisect debugging, worktrees, submodules, hooks, filter-branch, and patch workflows.

Last Updated: May 1, 2025

Reflog Recovery

git reflog
Show history of all HEAD movements (local, 90 days)
git reflog show branch
Show reflog for a specific branch
git checkout HEAD@{2}
Check out where HEAD was 2 moves ago
git branch recovered HEAD@{1}
Create a branch pointing to a lost commit
git reflog expire --expire=now --all
Clear reflog entries (use with caution!)
git fsck --lost-found
Find dangling commits not in any branch

Bisect Debugging

git bisect start
Begin binary search for bug-introducing commit
git bisect bad HEAD
Mark current commit as bad (has the bug)
git bisect good v1.0
Mark known-good commit (before bug appeared)
git bisect good
Mark current checked-out commit as good
git bisect run ./test.sh
Fully automated bisect — script returns 0=good
git bisect log
Show bisect progress log
git bisect replay logfile
Replay a previous bisect session
git bisect reset
End bisect and return to original HEAD

Worktrees

git worktree add ../path branch
Create a new working directory for a branch
git worktree list
List all worktrees with their branches and paths
git worktree remove ../path
Remove a worktree (clean up after done)
git worktree prune
Prune worktree entries for deleted directories
git worktree add -b new-branch ../path
Create worktree with a new branch
cd ../path
Switch context without stashing — ideal for hotfixes

Hooks & Filter-Branch

nano .git/hooks/pre-commit
Edit the pre-commit hook (add linting, tests)
chmod +x .git/hooks/pre-commit
Make hook executable (required!)
git filter-branch --tree-filter cmd
Rewrite history applying command to each commit
git filter-repo --path file --invert-paths
Modern alternative: remove file from history
git format-patch -3 HEAD
Generate .patch files for last 3 commits
git am *.patch
Apply patches from mailbox (preserves authorship)
Pro Tip: The reflog is your safety net — it records every HEAD movement for 90 days. If you lose commits, `git reflog` will find them.