ProgramGuru

Undo safely with restore, reset and revert

Undo safely with restore, reset and revert

The word 'undo' hides several different jobs. Git gives you different tools depending on whether the mistake is only in the working tree, staged, locally committed or already shared.

What you’ll learn

  • Distinguish restore, reset and revert.
  • Unstage without losing a working edit.
  • Undo shared work without casually rewriting history.

Undo by location

  1. Working tree

    Discard an unstaged edit.

    git restore
  2. Staging area

    Unstage while keeping the edit.

    git restore --staged
  3. Shared history

    Add an inverse commit.

    git revert
git revert

Undo based on where the mistake lives

git restore file can discard unstaged working-tree changes. git restore --staged file removes a path from the staging area while keeping the working edit.

git reset can move the current branch reference and optionally change the index/working tree; it is powerful and can discard work. git revert <commit> creates a new commit that applies the inverse change, making it a common choice for undoing a published commit without rewriting shared history.

Match the tool to the state

Run this in a disposable practice repository unless the lesson explicitly says otherwise.

git restore --staged notes.txt
# keep the working edit, remove it from the next commit

git restore notes.txt
# discard unstaged changes in notes.txt

git revert <commit-hash>
# create a new inverse commit

The first restore changes the staging area; the second changes the working tree. Revert works at commit-history level by adding a new commit.

Practice: Restore, reset and revert

Your task: Create a disposable repository and test four states: unstaged edit, staged edit, unpushed commit and published/shared commit. For each, write the least destructive undo command you would prefer.

Common pitfall to avoid

Be especially careful with git reset --hard. It can discard staged and working-tree changes. Inspect git status and create a backup branch when unsure.

Check your understanding

Which operation is generally safest for undoing a shared commit while preserving history?
Choose one answer. You can try again.

Answer and explanation

git revert

Correct. It records an inverse change as a new commit.

Restore, reset and revert: what to remember

Undo safely with restore, reset and revert is complete when you can explain the state being changed before you run the command, not merely repeat the syntax.

Read further: official supporting documentation.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Temporarily set aside work with git stash →