Q15 of 40 · Git

What is the difference between `git revert` and `git reset`, and when should you use each?

GitMidgitrevertresethistorysafety

Short answer

Short answer: `git revert` creates a new commit that undoes a previous commit — safe for shared history. `git reset` moves HEAD (and optionally the index/working tree) to an earlier commit — rewrites history, dangerous on shared branches.

Detail

git revert is the safe undo tool for public branches. It reads the diff introduced by the target commit, inverts it, and records that inversion as a new commit. The old commit remains in history, so collaborators who already pulled are unaffected. You can revert a merge commit with -m 1.

git reset moves the branch pointer itself, effectively erasing commits from the branch tip. The three modes control what happens to the changes: --soft keeps them staged, --mixed (the default) keeps them unstaged in the working tree, and --hard discards them entirely. Because reset rewrites the branch tip, anyone who has already pulled those commits will diverge — a force-push would then be required, which is disruptive on shared branches.

Decision rule: if the commit has been pushed to a shared remote, always prefer git revert. Use git reset only for local clean-up (tidying up commits you haven't pushed yet) or in an emergency rollback on a branch you own exclusively. In a CI/CD pipeline, a revert commit is also visible in the audit trail, which matters for compliance.

// EXAMPLE

# --- git revert: safe for shared history ---
# Undo a specific commit by SHA (creates a new "Revert" commit)
git revert a1b2c3d4

# Revert a range (oldest..newest — note: exclusive of oldest)
git revert a1b2c3d4..HEAD

# Revert a merge commit — '-m 1' means "keep parent 1 (the main branch)"
git revert -m 1 mergeCommitSha

# --- git reset: rewrites history — local use only ---
# Move HEAD back 2 commits, keep changes STAGED
git reset --soft HEAD~2

# Move HEAD back 2 commits, keep changes UNSTAGED (default)
git reset HEAD~2

# Move HEAD back 2 commits, DISCARD all changes (destructive!)
git reset --hard HEAD~2

// WHAT INTERVIEWERS LOOK FOR

Understanding that revert is additive (safe for shared branches) while reset is destructive (rewrites history). Knowing the three reset modes. Mentioning the -m flag for reverting merge commits is a strong signal.

// COMMON PITFALL

Using `git reset --hard` on a pushed commit and then force-pushing, which overwrites teammates' history. Always revert on shared branches.