Which undo is safe depends on one question: has anyone else seen this history? On shared branches, add a corrective commit; rewrite only work nobody else has.1

Pushed or deployed mistakes: revert

git revert <bad-commit> creates a new inverse commit and keeps an auditable history, so it suits shared branches and post-release fixes. Reverting a merge needs a mainline parent such as -m 1, agreed with the team.1 The same reasoning rules out --amend on a commit others have already pulled.2

Local mistakes: reset

CommandHistoryIndexWorking treeUse
git reset --soft HEAD~1Moves backKeepsKeepsReorganize the latest unshared commit
git reset --mixed HEAD~1Moves backClearsKeepsRestage selected content (the default)
git reset --hard HEAD~1Moves backOverwritesOverwritesHigh risk: only confirmed-unneeded, unshared work

As tabled in the reference. Never reset and force-push a shared main or release branch.1

Recovery and investigation

  • git reflog shows where HEAD pointed before; inspect a candidate commit and protect it with a new recovery branch. Reflog is local and expires.
  • git blame finds the last commit that changed a line (not who is responsible); git bisect binary-searches a regression; always finish with git bisect reset.1

High-risk operations

OperationSafer practice
git push --force--force-with-lease on a personal branch, after fetching; never a licence to force-push shared branches
git reset --hardCheck status, diff, reflog; branch or stash what you may need
Deleting a remote branchCheck PRs, deployments, protection rules; get authorisation
git clean -fdPreview with git clean -nd

As tabled in the reference. Its pre-flight checklist asks: right repository and branch, anything unsaved, fresh remote state, shared or personal branch, a safer mechanism available, a recovery point, and whether production, releases, or credentials are involved.1

Footnotes

  1. Essential Git Commands for Operations, original ↩ ↩2 ↩3 ↩4 ↩5

  2. Git command-line basics: git commit, original ↩