Undoing Changes in Git: reset, revert, checkout, and restore

Compare Git reset, revert, checkout, and restore, including reset mode effects, preflight steps for destructive commands, and recovery guidance for shared history.

published: reading time: 36 min read author: Geek Workbench updated: November 12, 2026
Quick Summary

Git offers several ways to undo work, and their effects differ. Reset moves HEAD; soft keeps changes staged, mixed leaves tracked edits unstaged, and hard makes the index and tracked worktree match the target. Revert adds a new commit, but may conflict or trigger CI and deployment side effects. Inspect status, preserve work, and confirm the target before destructive commands.

Introduction

Every developer has been there: you committed to the wrong branch, staged the wrong files, or pushed a change that broke production. Git provides several commands for undoing changes, but they work in fundamentally different ways and choosing the wrong one can cause data loss or break your team’s workflow.

The key distinction is between rewriting history and creating a new commit that reverses a change. Rewriting a published branch can disrupt collaborators who based work on the old commits. A revert keeps those commits visible, but it can conflict with later changes and a new commit may trigger hooks, CI, or deployment workflows. Inspect the current state and the target before choosing either operation.

This guide covers git reset (with its three modes), git revert, git checkout, and the modern git restore command. You will learn when to use each, how they interact with the three-state model, and how to recover from mistakes. For the conceptual foundation, see The Three States.

When to Use / When Not to Use

Use git reset when:

  • Undoing local, unpushed commits
  • Unstaging files (--mixed or --soft)
  • Discarding local commits you no longer want
  • Squashing commits before pushing

Use git revert when:

  • Undoing commits that have been pushed to a shared branch
  • Recording an explicit undo commit after reviewing its effects
  • Reverting a specific commit in the middle of history

Use git restore when:

  • Discarding uncommitted changes in the working directory
  • Unstaging files (modern replacement for git reset HEAD)
  • Restoring files from a specific commit

Use git checkout when:

  • Switching branches (its primary purpose)
  • Restoring individual files from a specific commit (legacy syntax)

Core Concepts

The undo commands operate at different levels of the three-state model:


graph LR
    A[Working Directory] -->|git restore / git checkout| B[Discard changes]
    A -->|git add| C[Staging Area]
    C -->|git restore --staged| A
    C -->|git reset --mixed| A
    C -->|git reset --soft| D[Repository HEAD]
    D -->|git reset --mixed| C
    D -->|git reset --hard| A
    D -->|git revert| D

Three Modes of git reset

git reset has three modes that determine what happens to your staging area and working directory when you move HEAD backward. The mode you choose depends entirely on whether you want to keep your changes staged, unstaged, or discarded.

--soft is the gentlest option. It moves HEAD back one commit but leaves your staging area and working directory exactly as they were. Your changes are still staged and ready to recommit. This is useful when you want to add a forgotten file to a commit or combine multiple commits into one.

--mixed (the default) moves HEAD back and resets the index to the target, while leaving the working tree as it is. Changes that were in the undone commit remain as unstaged edits. This is useful when you committed too early and want to review or stage the changes again.

--hard moves HEAD, replaces the index, and updates tracked files in the working tree to match the target. That discards staged and unstaged changes to tracked files. Untracked files generally remain unless they obstruct files Git needs to write; removing untracked files requires a separate git clean command. The reflog may help recover earlier commit positions, but it does not save uncommitted file contents. Check git reset’s mode details before using it.


graph TD
    A[Commit C3<br/>HEAD points here] -->|git reset --soft HEAD~1| B[HEAD moves to C2<br/>Changes stay STAGED]
    A -->|git reset HEAD~1| C[HEAD moves to C2<br/>Changes stay UNSTAGED<br/>in working directory]
    A -->|git reset --hard HEAD~1| D[HEAD moves to C2<br/>Tracked edits are discarded<br/>working directory matches C2]

reset vs revert

The fundamental distinction in Git undo operations is between rewriting history and creating a new commit. git reset moves the branch pointer, so commits after the target become unreachable from that branch, though a reflog or other ref may still retain them. git revert adds a commit that attempts to reverse the target’s changes while leaving the original commit in history.

For local, unpushed commits, reset can be appropriate after you confirm what will move and preserve any work you need. For a shared branch, revert usually avoids rewriting commits that others may have fetched. It is not automatic or always safe: it may conflict, and the resulting commit can retrigger CI, deployments, or other automation. Review the change and coordinate with the team before pushing it. See the official git revert documentation.

The diagram below shows what happens when you reset versus revert a bad commit. With reset, the bad commit leaves the branch tip’s history. With revert, it stays in history and a new commit attempts to reverse its effect.


graph LR
    A[C1] --> B[C2]
    B --> C[C3<br/>Bad commit]

    C -->|git reset --hard C2| D[C1 --> C2<br/>C3 leaves branch history<br/>History rewritten]
    C -->|git revert C3| E[C1 --> C2 --> C3 --> C4<br/>C4 undoes C3<br/>History preserved]

Architecture or Flow Diagram

Decision Tree: Which Undo Command?


graph TD
    A[Need to undo something?] --> B{Is the commit pushed/shared?}
    B -->|Yes| C[Use git revert]
    B -->|No| D{What level?}

    D -->|Working directory| E[Use git restore file]
    D -->|Staging area| F[Use git restore --staged file]
    D -->|Last commit| G{Keep changes?}

    G -->|Yes, staged| H[git reset --soft HEAD~1]
    G -->|Yes, unstaged| I[git reset HEAD~1]
    G -->|No, discard| J[git reset --hard HEAD~1]

    D -->|Specific commit| K[git revert <commit>]
    D -->|Switch branches| L[git switch branch]

Typical Effects by Command


graph LR
    A[History-preserving] --> B[git revert<br/>may conflict or trigger automation]
    B --> C[git reset --soft]
    C --> D[git reset --mixed]
    D --> E[git restore --staged]
    E --> F[git restore file]
    F --> G[git reset --hard]
    G --> H[Discards tracked local changes]

Step-by-Step Guide / Deep Dive

The preflight examples below use patch files outside the repository. Choose unused filenames each time; git diff and git diff --cached save tracked changes, while untracked files need separate copies. A rescue branch records a commit, not working-tree contents. Check status, save what you need, and verify the branch and target immediately before an operation that rewrites history or discards files.

git reset: Three Modes

Soft Reset: Undo Commit, Keep Changes Staged


# Scenario: You committed but want to add more files to the same commit

# Preflight: inspect status, save tracked edits to new patch paths, create a
# unique rescue ref, and confirm HEAD~1 is the local commit to move past.
git status --short --branch
git diff --binary > ../before-soft-reset-worktree.patch
git diff --cached --binary > ../before-soft-reset-index.patch
git branch rescue-before-soft-reset HEAD
git log --oneline --decorate -n 5

# Undo the last commit, keep all changes staged
git reset --soft HEAD~1

# Now you can add more files and re-commit
git add additional-file.py
git commit -m "feat: complete feature with all files"

# Result: One clean commit instead of two

The soft reset moves HEAD back one commit but leaves both the staging area and working directory untouched. Your changes are still staged, ready to be committed again.

Mixed Reset: Undo Commit, Keep Changes Unstaged


# Scenario: You committed but want to restage changes selectively

# Preflight: inspect status, save staged and unstaged work to new patch paths,
# create a unique rescue ref, and confirm the branch and target commit.
git status --short --branch
git diff --binary > ../before-mixed-reset-worktree.patch
git diff --cached --binary > ../before-mixed-reset-index.patch
git branch rescue-before-mixed-reset HEAD
git log --oneline --decorate -n 5

# Undo the last commit, keep changes in working directory (unstaged)
git reset HEAD~1
# Equivalent to: git reset --mixed HEAD~1

# Review what changed
git status
git diff

# Stage only the changes you want
git add -p src/app.py

# Commit selectively
git commit -m "feat: partial feature implementation"

The mixed reset (default mode) moves HEAD back and unstages all changes. Your working directory is untouched — you still have all your changes, just not staged.

Hard Reset: Undo Commit, Discard Tracked Edits


# Scenario: You intend to move HEAD back and discard tracked local edits

# Preflight: choose unused patch paths and a unique rescue ref outside the
# current work. Save untracked files separately; review branch and target.
git status --short --branch
git diff --binary > ../before-reset-worktree.patch
git diff --cached --binary > ../before-reset-index.patch
git branch rescue-before-reset HEAD
git log --oneline --decorate -n 5

# Confirm the branch and target. --hard discards tracked staged and unstaged edits.
git reset --hard HEAD~1

The hard reset moves HEAD and makes the index and tracked working-tree files match the target. Staged and unstaged edits to tracked files are discarded. Save a patch or create a rescue ref and inspect untracked files separately before running it. A reflog can help recover a commit that became unreachable; it does not restore uncommitted file contents.

git revert: Undo a Commit Without Rewriting History


# Preflight: inspect status and the target commit; save local work before
# starting. Confirm the revert's effect with the team if this is a shared branch.
git status --short --branch
git diff --binary > ../before-revert-worktree.patch
git diff --cached --binary > ../before-revert-index.patch
git show --stat --oneline HEAD

# Revert the last commit; review the new commit and its downstream effects.
git revert HEAD

# Revert a specific commit
git revert abc1234

# Revert a range of commits
git revert abc1234..def5678

# Revert without opening the editor (auto-generate message)
git revert --no-edit abc1234

# Revert a merge commit (requires specifying the parent)
git revert -m 1 abc1234  # -m 1 means revert relative to first parent

git revert creates a new commit that applies the inverse of the specified commit. Conflicts can require manual resolution, and a revert commit may retrigger hooks, CI, deployments, or other automation. It also cannot undo external effects such as a message already sent or a migration already applied. Review the result and any downstream behavior before pushing; see the git revert reference.

git restore: Modern File-Level Undo

Introduced in Git 2.23, git restore separates the file-restoration functionality from git checkout:


# Preflight before discarding this file: use new patch paths outside the repo,
# inspect status, save any work you may want to keep, and confirm the source.
git status --short --branch
git diff --binary > ../before-restore-worktree.patch
git diff --cached --binary > ../before-restore-index.patch
git restore src/app.py

# This discards tracked worktree changes across the repository. Repeat the
# full preflight with new patch paths, review the patch, and confirm the scope.
git status --short --branch
git diff --binary > ../before-restore-all-worktree.patch
git diff --cached --binary > ../before-restore-all-index.patch
git restore .

# Unstage a file (move from staging area back to working directory)
git restore --staged src/app.py

# Restore a file from a specific commit
# Preflight: use new patch paths, inspect status, and confirm the source commit
# and file path. This replaces the working-tree file with the source version.
git status --short --branch
git diff --binary -- src/app.py > ../before-restore-from-commit-worktree.patch
git diff --cached --binary -- src/app.py > ../before-restore-from-commit-index.patch
git restore --source=abc1234 src/app.py

# With both flags, this restores the index and worktree from HEAD. Inspect
# status, save patches to new paths, and confirm the file path before running it.
git status --short --branch
git diff --binary -- src/app.py > ../before-restore-stage-worktree.patch
git diff --cached --binary -- src/app.py > ../before-restore-stage-index.patch
git restore --staged --worktree src/app.py

git checkout: Branch Switching and File Restoration


# Switch branches
git checkout feature-branch
# Modern alternative:
git switch feature-branch

# Create and switch to a new branch
git checkout -b new-feature
# Modern alternative:
git switch -c new-feature

# This overwrites the selected file. Inspect status and save a patch first;
# confirm the path and source before restoring it.
git status --short --branch
git diff --binary -- src/app.py > ../before-checkout-worktree.patch
git diff --cached --binary -- src/app.py > ../before-checkout-index.patch
git checkout -- src/app.py
# Alternative to the checkout command above; choose one command, not both.
# Repeat the preflight before restoring the path.
git status --short --branch
git diff --binary -- src/app.py > ../before-restore-alternative-worktree.patch
git diff --cached --binary -- src/app.py > ../before-restore-alternative-index.patch
git restore src/app.py

# Restore a file from a specific commit
# Preflight: inspect status, save staged and unstaged changes for this path to
# new patch files outside the repo, and verify the source commit and path.
git status --short --branch
git diff --binary -- src/app.py > ../before-restore-source-worktree.patch
git diff --cached --binary -- src/app.py > ../before-restore-source-index.patch
git checkout abc1234 -- src/app.py
# Alternative to the checkout command above; choose one command, not both.
# Repeat the preflight before restoring the path.
git status --short --branch
git diff --binary -- src/app.py > ../before-restore-specific-alternative-worktree.patch
git diff --cached --binary -- src/app.py > ../before-restore-specific-alternative-index.patch
git restore --source=abc1234 src/app.py

Common Undo Scenarios

Scenario 1: Committed to Wrong Branch


# You committed to main but should have been on feature

# Preflight: choose unused patch paths and a unique rescue ref; inspect status
# and confirm the current branch and target. This rewrites local history.
git status --short --branch
git diff --binary > ../before-reset-worktree.patch
git diff --cached --binary > ../before-reset-index.patch
git branch rescue-before-reset HEAD
git log --oneline --decorate -n 5
git reset --soft HEAD~1

# Switch to the correct branch
git switch feature

# Commit on the correct branch
git commit -m "feat: add feature"

Scenario 2: Forgot to Stage a File


# You committed but forgot a file

# Preflight the amend: choose unused patch paths and a unique rescue ref,
# inspect status, and confirm this commit is local and unshared.
git status --short --branch
git diff --binary > ../before-amend-worktree.patch
git diff --cached --binary > ../before-amend-index.patch
git branch rescue-before-amend HEAD
git log --oneline --decorate -n 3

# Add the forgotten file
git add forgotten-file.py

# Amend the last commit
git commit --amend --no-edit

Scenario 3: Committed with Wrong Message


# Preflight: choose unused patch paths and a unique rescue ref, inspect status,
# and confirm HEAD is unpushed.
git status --short --branch
git diff --binary > ../before-amend-worktree.patch
git diff --cached --binary > ../before-amend-index.patch
git branch rescue-before-amend HEAD
git log --oneline --decorate -n 3

# Fix the commit message
git commit --amend -m "Correct commit message"

Scenario 4: Want to Squash Last Two Commits


# Preflight: inspect status, save patches, create a rescue ref, and confirm
# the branch and the two commits being rewritten. Use only for local history.
git status --short --branch
git diff --binary > ../before-squash-worktree.patch
git diff --cached --binary > ../before-squash-index.patch
git branch rescue-before-squash HEAD
git log --oneline --decorate -n 5
git reset --soft HEAD~2

# Re-commit as one
git commit -m "feat: combined feature implementation"

Scenario 5: Discard All Local Changes


# Preflight: inspect status; save worktree and index patches to new paths
# outside the repo; copy untracked files you need; confirm branch and target.
git status --short --branch
git diff --binary > ../before-sync-worktree.patch
git diff --cached --binary > ../before-sync-index.patch
git branch rescue-before-sync HEAD
git fetch origin
git log --oneline --decorate -n 5 origin/main

# Confirm origin/main is the intended target. This discards tracked edits and
# moves the current branch; local commits after the target become unreachable.
git reset --hard origin/main

# Preview untracked files first; inspect the output before deleting anything.
# See the official git clean documentation for the effect of -n and -f.
git status --short --branch
git clean -nd
# Run only after confirming every listed untracked path can be removed.
git clean -fd

Production Failure Scenarios

Scenario Impact Mitigation
git reset --hard on shared branch Rewrites the branch tip; collaborators may have based work on the old commits Avoid uncoordinated resets; consider a revert after reviewing its effects
git reset --hard loses tracked work Staged and unstaged edits to tracked files are discarded Inspect status, save patches or a rescue ref, and confirm the target first
git revert on a merge commit without -m Git cannot infer the mainline parent Inspect the merge and choose the parent intentionally; the choice affects later merges
git checkout on uncommitted changes Changes may be overwritten or lost Use git stash before switching branches with uncommitted work
Reverting a commit that was already reverted Double-negative restores original changes Check git log to see if a revert commit already exists
Path-specific git reset Updates the index, not the worktree Use git restore to discard selected worktree paths after preflight

Trade-off Analysis

Approach Advantages Disadvantages When to Use
git reset --soft Preserves all changes staged, clean undo Rewrites branch history Squashing, amending, restaging local commits
git reset --mixed Preserves tracked worktree edits, allows selective restaging Requires restaging Restaging selectively, undoing local commits
git reset --hard Makes tracked files match a target Discards tracked staged and unstaged edits Discarding selected local work after preflight
git revert Adds an undo commit without moving shared history May conflict or retrigger automation Reversing a shared commit after review
git restore Clear intent, modern syntax Can discard tracked worktree edits Restoring selected paths after preflight
git checkout -- Works everywhere Ambiguous intent (switching vs restoring) Legacy scripts, older Git versions

Implementation Snippets

The Safe Undo Workflow

Before rewriting a commit or discarding tracked changes, inspect the repository state and target. A rescue branch preserves a commit reference; it does not preserve uncommitted edits, so save a patch or stash those separately. Keep the backup until you have checked the result.


# Preflight: choose unused patch paths and a unique rescue ref; copy untracked
# files separately. Confirm this is the intended branch and target.
git status --short --branch
git diff --binary > ../before-reset-worktree.patch
git diff --cached --binary > ../before-reset-index.patch
git branch backup-before-reset HEAD
git log --oneline --decorate -n 5

# After reviewing the saved work, confirm HEAD~3 is the intended target.
git reset --hard HEAD~3

# If recovering by moving this branch, inspect status and save any new work
# first; confirm the backup ref before using it as the target.
git status --short --branch
git diff --binary > ../before-recovery-worktree.patch
git diff --cached --binary > ../before-recovery-index.patch
git log --oneline --decorate backup-before-reset -n 3
git reset --hard backup-before-reset
# Keep the rescue ref until the restored result is verified.

Recovery with reflog

The reflog records recent updates to references in this local repository. Use it to find a commit that became unreachable after a reset or rebase, then verify the hash before recovering it. Reflog expiration depends on configuration; the default is 90 days for reachable entries and 30 days for unreachable entries. It is a recovery aid, not a backup, and it cannot restore uncommitted file contents. See the official git reflog documentation.


# See all HEAD movements (including resets)
git reflog

# Find the commit you lost
git reflog | head -20

# Before moving the current branch, inspect and preserve current work; replace
# abc1234 only after confirming it is the commit you want to recover.
git status --short --branch
git diff --binary > ../before-reflog-recovery-worktree.patch
git diff --cached --binary > ../before-reflog-recovery-index.patch
git branch rescue-before-reflog-recovery HEAD
git show --stat --oneline abc1234
git reset --hard abc1234

# Or cherry-pick it
git cherry-pick abc1234

Bulk Operations

Bulk reverts create commits one by one. Review the commit range first and expect the sequence to stop if a revert conflicts; earlier revert commits may already exist. A revert can also trigger hooks or CI for each new commit. For file-level cleanup, name the paths you intend to discard instead of building a shell command from every modified filename.


# Preflight: inspect status, save local work to new patch paths, create a
# unique rescue ref, and review the range and order before starting.
git status --short --branch
git diff --binary > ../before-bulk-revert-worktree.patch
git diff --cached --binary > ../before-bulk-revert-index.patch
git branch rescue-before-bulk-revert HEAD
git log --oneline --decorate v1.0.0..HEAD

# Revert the listed commits only after confirming the range and target.
git log --oneline v1.0.0..HEAD | while read hash msg; do
    git revert --no-edit $hash
done

# Preflight before discarding this named file: inspect status, save a patch,
# and confirm the path and source. Repeat for each file you intend to discard.
git status --short --branch
git diff --binary -- path/to/file > ../before-file-restore.patch
git diff --cached --binary -- path/to/file > ../before-file-restore-index.patch
git restore --worktree -- path/to/file

# Unstage all files
git restore --staged .

Interactive Undo

git rebase -i HEAD~N opens an editor listing your last N commits. You decide the fate of each one: pick keeps it, reword changes the message, edit pauses for manual changes, squash merges it with the one above, and drop removes it. You can also reorder commits by moving lines in the editor. Only use this on local, unpushed commits — running it on shared history rewrites what your teammates have already pulled, creating divergent branches that are painful to reconcile.


# Preflight: inspect status, save tracked changes to new patch files, create
# a unique rescue ref, and confirm these are local, unshared commits.
git status --short --branch
git diff --binary > ../before-rebase-worktree.patch
git diff --cached --binary > ../before-rebase-index.patch
git branch rescue-before-rebase HEAD
git log --oneline --decorate -n 8

# Interactive rebase to edit, squash, or drop commits
git rebase -i HEAD~5

# In the editor:
# pick = keep commit
# reword = keep but edit message
# edit = stop for manual changes
# squash = combine with previous
# fixup = combine, discard message
# drop = remove commit

Observability Checklist

  • Recovery: Inspect git reflog for recent local ref updates; entries expire and do not preserve uncommitted file contents
  • Metrics: Track the frequency of git reset --hard — high frequency indicates workflow issues
  • Traces: Use git log --oneline before and after undo operations to verify the result
  • Alerts: Pre-push hooks should warn about force-push requirements after resets
  • Audit: Do not treat a local reflog as a shared audit log; use your organization’s review and logging controls
  • Health: Periodically check git status to ensure no unintended state changes
  • Validation: After any undo operation, run tests to verify the codebase is still functional

Security & Compliance Considerations

  • git reset --hard changes visible history: Follow team policy before moving a shared branch. Other refs, reflogs, and clones may still retain the commit.
  • Reflog is local: git reflog is not shared with remotes. Each developer has their own reflog. It is not a substitute for proper audit logging
  • Reverted commits remain visible: git revert preserves the original commit and adds a reversal commit to that branch. Follow your organization’s audit requirements separately.
  • Force-push after reset: Rewriting a published branch requires a non-fast-forward update if you decide to update the remote. Coordinate with branch owners and everyone who may have based work on that history first. Git’s --force-with-lease option can reject an update when the remote ref no longer matches the expected value, but it does not replace coordination.
  • Sensitive data removal: git reset --hard changes refs and tracked files; it is not a secure-erasure operation. Use the repository host’s process and a dedicated history-cleanup procedure when sensitive data requires remediation.

Common Pitfalls / Anti-Patterns

  • Using git reset --hard as a reflex: It discards tracked staged and unstaged edits. Consider --soft or --mixed if you need to keep them.
  • Resetting published commits: This rewrites branch history and can disrupt collaborators. Prefer a reviewed revert for shared history, or coordinate before an approved rewrite.
  • Confusing git checkout and git restore: git checkout does two things (switch branches and restore files), which is confusing. Use git switch for branches and git restore for files
  • Relying on reflog as a backup: It may help recover a recent commit, but entries expire and it does not preserve uncommitted work.
  • Reverting without understanding conflicts: A revert may conflict with subsequent changes. Always review the result of git revert before committing
  • Using the wrong command for a path: Path-limited git reset updates the index; it does not discard the worktree copy. Use git restore --worktree -- <path> only after checking and saving the changes you intend to discard.
  • Forgetting that git revert creates a new commit: The undo is itself a commit. This means reverting a revert restores the original changes

Quick Recap Checklist

  • git reset --soft moves HEAD back, keeps changes staged
  • git reset --mixed (default) moves HEAD back, keeps changes unstaged
  • git reset --hard moves HEAD and discards staged and unstaged edits to tracked files; untracked files are separate
  • git revert creates a new commit, but may conflict or trigger automation
  • git restore file discards uncommitted changes in a file
  • git restore --staged file unstages a file
  • git checkout is primarily for switching branches (use git switch instead)
  • git reflog may help recover a recent commit; it is local and expires
  • Avoid rewriting published shared commits without coordination; use a reviewed revert when it fits the intended change
  • Inspect status, save a patch or rescue ref, and confirm the target before destructive operations
  • Use git revert to record an undo commit when appropriate; follow audit policy separately
  • git reset --hard origin/main moves the current branch and discards tracked edits; confirm the fetched remote target first

How Reset Moves HEAD, Index, and Working Tree

git reset operates by moving the HEAD reference and optionally updating the index (staging area) and working directory. Understanding exactly what each mode touches is critical to using reset safely:


graph TD
    A[HEAD points to C3] --> B{reset mode?}
    B -->|--soft| C[HEAD moves to C2<br/>Index = C3 snapshot<br/>Working tree = C3 snapshot]
    B -->|--mixed| D[HEAD moves to C2<br/>Index = C2 snapshot<br/>Working tree = C3 snapshot]
    B -->|--hard| E[HEAD moves to C2<br/>Index = C2 snapshot<br/>Working tree = C2 snapshot]

    C --> F[Changes preserved as STAGED]
    D --> G[Changes preserved as UNSTAGED]
    E --> H[Tracked edits discarded; commits may remain in reflog or other refs]
  • --soft: Only HEAD moves. Index and working tree keep the content of the original commit. Your changes appear as staged.
  • --mixed (default): HEAD and index move. Working tree keeps the original content. Your changes appear as unstaged modifications.
  • --hard: HEAD, index, and tracked working-tree files all move to the target. Staged and unstaged tracked edits are discarded; untracked files generally remain unless they obstruct a tracked path.

Production Failure: git reset --hard on Shared Branch

A senior developer notices a bad commit on the shared develop branch. They run git reset --hard HEAD~2 and force-push without coordinating. This moves the shared branch tip away from commits collaborators may have used. They may need to reconcile their local branches and recover any work based on the old tip.

  • Branch tips diverge — collaborators may still have the old commits in their clones, while the remote points to rewritten history
  • Reconciliation is required — each person must compare local work with the new remote branch before pushing or pulling
  • Unpushed commits need recovery — a reset or later cleanup may make them unreachable from a branch, though another ref or reflog may retain them
  • The remote no longer shows the removed commits — a force-push changes the branch ref, but does not remove copies from clones

What should have happened: use a revert after checking the target and current work. A revert can still conflict, and its new commit may run CI or deployment workflows. Review the effect before pushing.


# Preflight: inspect status and save any local changes to new patch paths.
# Confirm the commits to reverse and coordinate with the branch owners.
git status --short --branch
git diff --binary > ../before-shared-revert-worktree.patch
git diff --cached --binary > ../before-shared-revert-index.patch
git log --oneline --decorate -n 10 develop

# Revert only after reviewing the targets; resolve conflicts if Git stops.
git revert abc1234
git revert def5678
git push origin develop

For a shared branch, prefer a revert when it fits the intended change, but review conflicts and downstream effects. If history rewriting is necessary, coordinate with branch owners and affected collaborators before any force-push. Review the current remote ref; --force-with-lease can guard against overwriting an unexpected remote tip but does not replace coordination.

Trade-offs: reset vs revert vs restore

Command What it does Safety level History impact When to use
git reset --soft Moves HEAD back, keeps changes staged Safe (local only) Rewrites local history Squashing commits, fixing last commit
git reset --mixed Moves HEAD back, unstages changes Safe (local only) Rewrites local history Restaging selectively, undoing commit
git reset --hard Moves HEAD back; discards tracked edits Destructive Rewrites local history Discarding tracked local work after preflight
git revert Adds a commit that reverses a change Review required Preserves prior commits Undoing a shared commit when the resulting change is appropriate
git restore Restores selected paths or unstages Can discard edits No commit history change Restoring paths after preflight
git checkout Switches branches or restores files Safe No history impact Branch switching (use git switch instead)

Using Reset and Revert on Shared Branches

In teams with audit requirements, branch history is only part of the record. git reset moves a branch ref and can remove commits from that branch’s visible history; reflogs and other refs may still retain them. git revert adds a commit that records the reversal, but does not by itself meet an organization’s audit requirements:

  • Audit trail: A revert commit records the reversal in that branch. A reset changes which commits the branch points to; it does not erase every copy or log.
  • Review: A signed revert records its author and commit metadata, but does not by itself prove that a change was authorized.
  • Compliance requirements: Follow the controls that apply to your organization; do not assume that a revert commit alone satisfies them.
  • Team accountability: A revert appears as a new commit on the branch. A reset changes the branch’s visible history; retain review records and coordinate the change through the team’s normal process.

Policy recommendation: Protect shared branches from uncoordinated force-pushes. Use revert when it preserves the intended history, and document the review and coordination required for any approved rewrite.

Interview Questions

1. What is the difference between `git reset` and `git revert`?

git reset moves the branch pointer and may make later commits unreachable from that branch; a reflog or another ref may still retain them. git revert adds a commit that applies the inverse change while leaving the original commit in history. Reset can suit unshared local commits after preflight. Revert often fits shared history, but it can conflict or trigger CI and deployment workflows. Review the result before pushing.

2. What happens to your changes with `git reset --soft`, `--mixed`, and `--hard`?

--soft moves HEAD but leaves the index and working tree unchanged, so changes appear staged. --mixed (the default) moves HEAD and resets the index to the target while leaving working-tree files unchanged, so the changes appear unstaged. --hard also updates tracked working-tree files to match the target, discarding staged and unstaged edits to those files. Untracked files generally remain. See the Git reset reference for exact behavior.

3. How do you recover a commit that was lost after `git reset --hard`?

Use git reflog to find a recent commit position, then verify the hash. Before moving the branch again, inspect status, preserve current work, and confirm the target. The default expiration is 90 days for reachable entries and 30 days for unreachable entries, but configuration can change those periods. The reflog is local and does not preserve uncommitted file contents. See the Git reflog reference.

4. Why is `git restore` preferred over `git checkout --` for file restoration?

git checkout can switch branches or restore files, depending on its arguments. git restore (introduced in Git 2.23) makes file restoration explicit; use git switch for branches. The older git checkout -- <path> form remains available, but inspect status and preserve work before restoring a file.

5. What is the safest workflow for undoing a pushed commit on a shared branch?

For shared history, a revert often avoids moving the branch away from commits other people may have fetched. Inspect the target and current work first; a revert may conflict or retrigger CI, deployments, and other automation. Review the resulting commit and coordinate with the team before pushing. If an approved history rewrite is necessary, coordinate before force-pushing; --force-with-lease is a guard against an unexpected remote tip, not a substitute for coordination. Save uncommitted work separately from a rescue branch.

6. When should you use `git reset --hard` versus `git reset --mixed`?

Use --hard only when you intend to move HEAD and overwrite tracked files to match the target. It discards staged and unstaged edits to tracked files; untracked files generally remain. Before using it to match a remote branch, inspect status, save a patch or rescue ref, fetch and verify the target, and confirm the current branch. Use --mixed when you want to move HEAD and unstage changes while keeping the tracked working tree as it is.

7. How does `git revert` handle merge commits, and what pitfalls exist?

Reverting a merge commit requires -m to select the mainline parent. Inspect the parents and choose the one that matches the intended reversal; do not assume parent 1 is always correct. The choice affects later merges, and the revert may conflict with later changes. See the Git revert reference.

8. What is the difference between `git checkout -- file` and `git restore file`?

Both commands can replace a file in the working tree with a version from a commit, so either can discard local edits. git checkout -- file is legacy syntax that shares a command with branch switching. git restore file (Git 2.23+) makes file restoration explicit; git restore --staged unstages without replacing the working-tree file. Inspect status and save any edits before restoring.

9. What does `git reflog` show, and why is it important for recovery?

git reflog records recent updates to references in the local repository; it is not synced with remotes. After a reset, an earlier commit may remain reachable through a reflog entry or another ref. Confirm the hash and preserve current work before resetting to it. Default expiration is 90 days for reachable entries and 30 days for unreachable ones, but configuration can change these periods. The reflog does not preserve uncommitted file contents.

10. How does `git stash` interact with `git reset` and when should you use it?

git stash saves tracked staged and unstaged changes for later reapplication; untracked files require an option such as -u. Before git reset --hard, inspect status and save a patch or a rescue ref for the commit, plus any untracked files you need. git stash pop reapplies a stash and removes its entry if successful; git stash list shows available entries.

11. What are the compliance implications of using `git reset` in regulated industries?

Requirements depend on the organization and the rules that apply to it. git reset moves a branch ref and can remove commits from that branch's visible history; git revert adds a commit that records the reversal. Neither command alone establishes whether change-control or audit requirements have been met. Follow your organization's policy, and protect shared branches against uncoordinated force-pushes.

12. Why should you avoid using `git reset` on a subdirectory, and what happens?

git reset <tree-ish> -- <path> updates the index entry for that path; it does not move HEAD or discard the working-tree copy. For selective worktree restoration, use git restore --worktree -- <path> after checking and saving the edits you intend to discard. See the Git reset reference.

13. How does `git restore --staged` differ from `git reset HEAD`?

Both commands unstage a file — moving it from the staging area back to the working directory. The difference is purely syntactic: git reset HEAD <file> is the legacy form (the HEAD argument can be confusing), while git restore --staged <file> is the modern form introduced in Git 2.23 with clearer intent. git restore --staged also supports restoring a file from a specific commit with --source, which git reset cannot do.

14. What happens when you `git revert` a commit that has already been reverted?

Reverting a revert creates a double-negative that restores the original changes. This can be intentional (undoing an undo) but is usually accidental. Always check git log before reverting to see if a revert commit already exists for the target. When you need to undo a revert, either cherry-pick the original commit or revert the revert commit — do not attempt to revert the original commit again.

15. What should you consider when comparing undo commands?

There is no universal safety ranking: the effect depends on your current work, target, branch, and downstream automation. git revert preserves prior commits but may conflict or retrigger workflows. git reset --soft and --mixed move HEAD while preserving tracked worktree content; git reset --hard and git restore file can discard tracked edits. Inspect status, save work, and verify the target before choosing.

16. How does `git clean -fd` relate to `git reset --hard`, and when is it used together?

git reset --hard moves the current branch and makes tracked files match the target; it generally leaves untracked files alone. git clean -fd removes untracked files and directories. Before either command, inspect status, preserve work, and confirm the target. Preview untracked-file removal with git clean -nd and review the output before using -fd. Do not combine these commands as a routine sync step without checking what local data they will remove.

17. What is the `--source` flag in `git restore` and when would you use it?

git restore --source=<commit> <file> restores a file from a specific commit rather than from HEAD. For example, git restore --source=HEAD~3 --staged src/app.py takes the version of src/app.py from three commits ago, stages it, but leaves the working directory unchanged. This is useful for recovering an old version of a file, comparing changes across commits, or selectively cherry-picking file states without affecting the current working tree.

18. What are the dangers of force-pushing after a `git reset` on a shared branch?

If you intend to replace a published remote ref after rewriting its history, the update will be non-fast-forward. Coordinate with branch owners and collaborators before attempting it; they may have based work on the old tip. Review the current remote value first. git push --force-with-lease can reject an update when the remote ref differs from the expected value, but it is not a substitute for coordination or a review of the new history. See the Git push reference.

19. How does interactive rebase (`git rebase -i`) relate to undoing commits, and when is it preferred over reset or revert?

git rebase -i HEAD~N opens an editor showing the last N commits, where you can pick (keep), drop (remove), squash (combine), reword (change message), or edit (pause for changes) commits. It is useful for cleaning up a sequence of local commits before sharing them, such as squashing fixup commits, reordering commits, or editing messages. Like reset, it rewrites history; keep it to local, unshared commits unless the team has agreed to replace published history and coordinate the remote update.

20. Under what conditions does a `git revert` operation produce merge conflicts?

Revert conflicts occur when the lines changed by the commit being reverted have been modified by subsequent commits after the target commit. Git cannot cleanly apply the inverse changes because the surrounding context has changed. To resolve: manually edit the conflicting files to produce the desired state, then git add and git revert --continue. Always review the result of a revert before completing it — conflicts are a signal that the revert may need more nuanced handling than a straightforward inverse.

Further Reading

Conclusion

Choose the command by checking what it changes, what work it may discard, and whether others share the branch. Save work before destructive operations, confirm the target, and use the reflog only as a recovery aid. A reset can lose uncommitted tracked edits, and a pushed commit may remain in other clones even after a branch is rewritten.

Category

Related Posts

Centralized vs Distributed VCS: Team Trade-offs

Compare centralized and distributed version control by offline work, repository size, access control, branching, review, and migration effort.

#git #version-control #svn

Automated Changelog Generation

Generate release notes from structured commits, choose a release policy, and add changelog generation to CI without treating every merge as a release.

#git #version-control #changelog

Choosing a Git Team Workflow

Compare trunk-based development, short-lived feature branches, and release branches against your release, review, rollback, and compliance needs.

#git #version-control #branching-strategy