Undoing things safely
Pick the right tool
| Situation | Command | Rewrites history? |
|---|---|---|
| Discard uncommitted changes in a file | git restore file |
No |
| Unstage a file | git restore --staged file |
No |
| Fix the last local commit | git commit --amend |
Yes (local only) |
| Move branch back, keep changes staged | git reset --soft HEAD~1 |
Yes |
| Move back, keep changes unstaged (default) | git reset --mixed HEAD~1 |
Yes |
| Move back and discard changes | git reset --hard HEAD~1 |
Yes — destructive |
| Undo a commit that's already pushed/shared | git revert <sha> |
No — adds a new inverse commit |
| Undo a merge commit on main | git revert -m 1 <merge-sha> |
No |
| Copy a specific commit to another branch | git cherry-pick <sha> |
No (new commit) |
| Recover something "lost" | git reflog then branch/reset |
— |
The interview staple: "How do you undo a bad commit that's already on main?" → git revert, because it creates a new commit and doesn't rewrite shared history; everyone simply pulls it. In GitOps, reverting the commit is also how you roll back a deployment.
Reverting a merge (-m 1 keeps the first parent, i.e. main's side) has a catch: if you later want to re-merge that branch, Git thinks those changes are already merged — you must "revert the revert".
Force pushes
git push --forceoverwrites the remote branch with your version — anyone else's newer commits there are lost.git push --force-with-leaserefuses if the remote branch moved since you last fetched — always prefer it.- Protect
mainand release branches from force pushes and deletion with branch protection rules.
Recovering from someone's force-push to main: find the previous tip from your own reflog, a teammate's clone, the CI system's build records, or the hosting platform's activity log/API (GitHub shows force-push events in PRs and the audit log), then push it back (with protection temporarily lifted) and turn on protection.
A secret was committed
- Rotate the secret immediately — assume it's compromised the moment it was pushed. Removing it from Git doesn't un-leak it (forks, clones, CI logs, caches).
- Remove it from history if required:
git filter-repo --invert-paths --path config/prod.envor BFG Repo-Cleaner, then force-push and ask everyone to re-clone; on GitHub, contact support to purge cached views. - Prevent recurrence: pre-commit hooks (gitleaks, detect-secrets), GitHub push protection/secret scanning,
.gitignorefor env files, secrets from a secret manager instead of files.