Skip to content

Git cheat sheet

Terminal window
git status -sb
git switch -c feature/login
git add -p
git commit -m "feat: add login form"
git pull --rebase origin main
git push -u origin feature/login
git log --oneline --graph --decorate -20
git diff --staged
Terminal window
git log -p -- app/models/user.rb
git log --author="Felipe" --since="2 weeks ago"
git log -S"def login" --oneline
git blame app/models/user.rb
git show HEAD~2:app/models/user.rb
git diff main...feature/login
Terminal window
# Unstage a file, keep the change
git restore --staged app/models/user.rb
# Discard working-tree changes
git restore app/models/user.rb
# Amend the last commit message or contents
git commit --amend
# Undo the last commit but keep changes staged
git reset --soft HEAD~1
# Undo the last commit and keep changes unstaged
git reset HEAD~1
# Discard the last commit and its changes (danger)
git reset --hard HEAD~1
# Revert a commit safely on a shared branch
git revert <sha>
Terminal window
git fetch origin
git rebase origin/main
git rebase -i HEAD~5 # squash, reword, drop, reorder
git rebase --continue
git rebase --abort
Terminal window
# Move the last three commits onto main
git rebase --onto main HEAD~3

Rules of thumb:

  • Rebase local commits. Do not rebase a branch other people are pulling from.
  • Use --force-with-lease, never a bare --force, after a rebase.
  • Squash noise before opening a pull request.
Terminal window
git cherry-pick <sha>
git stash push -m "wip: login"
git stash list
git stash apply stash@{0}
git stash pop
git stash drop
Terminal window
git bisect start
git bisect bad
git bisect good v1.2.0
# test each checkout, then:
git bisect good
git bisect bad
git bisect reset
Terminal window
git log -S"undefined_method" --oneline
git grep "TODO" $(git rev-list --all)
Terminal window
git reflog # every place HEAD has been
git reset --hard HEAD@{3}
git checkout <sha> -- path/to/file
git fsck --lost-found

A lost commit is almost never lost: it is in the reflog until garbage collection.

Terminal window
git remote -v
git remote add upstream git@github.com:org/repo.git
git fetch --all --prune
git tag -a v1.0.0 -m "Release 1.0.0"
git push origin v1.0.0
Terminal window
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
git config --global pull.rebase true
git config --global rerere.enabled true
git config --global alias.lg "log --oneline --graph --decorate"
feat: add password reset
fix: handle nil user in session
refactor: extract token service
docs: explain deployment
test: cover expired tokens
chore: bump dependencies

A good commit explains why, not just what. The diff already says what changed.