Git cheat sheet
Everyday
Section titled “Everyday”git status -sbgit switch -c feature/logingit add -pgit commit -m "feat: add login form"git pull --rebase origin maingit push -u origin feature/logingit log --oneline --graph --decorate -20git diff --stagedInspecting history
Section titled “Inspecting history”git log -p -- app/models/user.rbgit log --author="Felipe" --since="2 weeks ago"git log -S"def login" --onelinegit blame app/models/user.rbgit show HEAD~2:app/models/user.rbgit diff main...feature/login# Unstage a file, keep the changegit restore --staged app/models/user.rb
# Discard working-tree changesgit restore app/models/user.rb
# Amend the last commit message or contentsgit commit --amend
# Undo the last commit but keep changes stagedgit reset --soft HEAD~1
# Undo the last commit and keep changes unstagedgit reset HEAD~1
# Discard the last commit and its changes (danger)git reset --hard HEAD~1
# Revert a commit safely on a shared branchgit revert <sha>Rebase and history
Section titled “Rebase and history”git fetch origingit rebase origin/maingit rebase -i HEAD~5 # squash, reword, drop, reordergit rebase --continuegit rebase --abort# Move the last three commits onto maingit rebase --onto main HEAD~3Rules 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.
Cherry-pick and stash
Section titled “Cherry-pick and stash”git cherry-pick <sha>git stash push -m "wip: login"git stash listgit stash apply stash@{0}git stash popgit stash dropFind the bug
Section titled “Find the bug”git bisect startgit bisect badgit bisect good v1.2.0# test each checkout, then:git bisect goodgit bisect badgit bisect resetgit log -S"undefined_method" --onelinegit grep "TODO" $(git rev-list --all)Recovery
Section titled “Recovery”git reflog # every place HEAD has beengit reset --hard HEAD@{3}git checkout <sha> -- path/to/filegit fsck --lost-foundA lost commit is almost never lost: it is in the reflog until garbage collection.
Remotes and tags
Section titled “Remotes and tags”git remote -vgit remote add upstream git@github.com:org/repo.gitgit fetch --all --prunegit tag -a v1.0.0 -m "Release 1.0.0"git push origin v1.0.0Configuration
Section titled “Configuration”git config --global user.name "Your Name"git config --global user.email "you@example.com"git config --global pull.rebase truegit config --global rerere.enabled truegit config --global alias.lg "log --oneline --graph --decorate"Commit message convention
Section titled “Commit message convention”feat: add password resetfix: handle nil user in sessionrefactor: extract token servicedocs: explain deploymenttest: cover expired tokenschore: bump dependenciesA good commit explains why, not just what. The diff already says what changed.