Git Cheatsheet
Daily Git commands for branching, staging, rebasing, inspecting history, and recovering from mistakes.
TL;DR
A quick reference for everyday Git workflows: creating branches with switch, staging partial changes, keeping history clean with rebase, and safely undoing mistakes with restore or revert.
Status and staging
git status --short # compact working-tree and index status
git diff # unstaged changes
git diff --staged # staged changes ready for the next commit
git add -p # interactively stage hunks
git restore <file> # discard unstaged edits in a tracked file
git restore --staged <file> # unstage without losing working-tree editsBranches and worktrees
git switch -c feat/login # create and switch to a new branch
git switch main # switch back to main
git branch -d feat/login # delete a merged branch (-D to force)
git worktree add ../wt-hotfix main # check out another branch in a separate directory
git worktree remove ../wt-hotfix # remove the extra worktree when donePrefer git switch and git restore over git checkout — they separate branch switching from file restoration and prevent accidental detached-HEAD edits.
Commits, rebase, and history
git commit -m "feat: add login"
git commit --amend --no-edit # fold staged changes into the last commit
git log --oneline --graph -n 15 # compact branch graph of recent commits
git fetch origin
git rebase origin/main # replay local commits on top of updated main
git push --force-with-lease # safe force-push after rebasing a private branchNever rebase or reset --hard commits that others have already pulled onto a shared branch. Use git revert <sha> to record an undo commit instead.
Undoing and recovering
| Goal | Command | Rewrites history? |
|---|---|---|
| Undo last commit, keep changes staged | git reset --soft HEAD~1 | Yes (local) |
| Undo last commit, keep changes unstaged | git reset HEAD~1 | Yes (local) |
| Undo a pushed commit safely | git revert <sha> | No |
| Temporarily shelve uncommitted work | git stash push -u -m "wip" | No |
| Find a lost commit after a bad reset | git reflog | No |
Check yourself
Check Yourself
1. You committed to a feature branch, pushed it, and someone else pulled it. How should you undo that commit?
2. Which command lets you inspect commits that are no longer reachable from any branch after an accidental reset?