Inspect state
git status # what changed, staged vs unstaged
git diff # unstaged changes
git diff --staged # staged changes
git log --oneline -10 # recent history
git log -p --follow file # history of one file with patches
git show <sha> # one commit, full diff
git blame file # who changed each line, when
Stage and commit
git add file.txt # stage one file
git add -p # stage hunks interactively
git add -A # stage everything, including deletions
git commit -m "message" # commit staged changes
git commit --amend # rewrite the last commit (unpublished only)
git restore --staged file # unstage, keep working copy
Branches and remotes
git switch -c feature # create and switch
git switch main # switch to existing branch
git branch -a # list local and remote branches
git branch -d old # delete merged local branch
git push -u origin feature # publish and set upstream
git fetch --prune # update remotes and remove stale refs
git pull --rebase # rebase local commits onto upstream
Undo and recover
| Goal | Command | Rewrites history? |
|---|---|---|
| Unstage a file | git restore --staged file | No |
| Discard working changes | git restore file | No |
| Amend the last commit | git commit --amend | Yes (local) |
| Undo a published commit | git revert <sha> | No (new commit) |
| Move branch back, keep changes | git reset --soft HEAD~1 | Yes (local only) |
| Move branch back, discard changes | git reset --hard HEAD~1 | Yes, destructive |
| Recover after a bad reset | git reflog then git reset --hard <sha> | Depends |
| Find the commit that broke it | git bisect start | No |
History-rewriting commands are safe only on commits that have not been pushed. If others may have the commit, use git revert.
Stash, tags and cleanup
git stash push -m "wip" # save work in progress
git stash list # list stashes
git stash pop # apply and drop the latest
git stash apply stash@{1} # apply a specific stash, keep it
git tag -a v1.2 -m "release"
git tag # list tags
git clean -nd # preview untracked files to be removed
git clean -fd # remove untracked files (destructive)
Recovery mental model
Git rarely loses committed data. reflog records where HEAD and branches have been, even after a hard reset or a deleted branch. The usual recovery sequence is: find the commit in git reflog, then create a branch or reset to it. Uncommitted changes have no such safety net — stash or commit before risky operations.
git reflog is local and expires after 90 days by default. Do not treat it as a permanent backup.