New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› Git› Undoing Mistakes Safely

Undoing Mistakes Safely

💻 Git

Restore files, unstage changes, amend commits and revert shared work without panic.

Lesson 8 of 9 Tutorial
0 of 9 completed

Almost every Git mistake is recoverable. The skill is choosing the right tool for the stage the change is in.

By the end of this lesson you can:
  • Discard working changes.
  • Unstage without deleting.
  • Revert a shared commit.

Working Directory

To throw away uncommitted changes in a file, restore it from the last commit.

git restore index.html
git restore .

Staged Changes

Unstage a file but keep its changes in the working directory.

git restore --staged index.html

Last Commit

If you have not pushed, amend the message or add a forgotten file. Do not amend a commit others already have.

git add forgotten.css
git commit --amend -m "Add homepage styles"

Shared Commits

git revert creates a new commit that undoes an earlier one. It is safe for shared history because it does not rewrite anything.

git revert a1b2c3d
Warning Avoid git reset --hard unless you are certain. It discards uncommitted work with no confirmation.

Practice

  1. Make a change, stage it, unstage it and discard it.
  2. Amend the message of your most recent unpushed commit.
  3. Revert a commit and inspect the new history.

Hands-on exercise

1. Create a commit with a typo in the message.
2. Amend the message.
3. Make a second commit that breaks something.
4. Revert the second commit and confirm the file is back to its previous state.

Recap

Restore for files, restore --staged to unstage, amend before pushing and revert for shared history.

Example

git restore index.html
git restore .

Exercises

Exercise 1. Recover a mistake Medium
1. Create a commit with a typo in the message.
2. Amend the message.
3. Make a second commit that breaks something.
4. Revert the second commit and confirm the file is back to its previous state.
Git exercise-1.txt
Expected Output
A clean history and a revert commit that restores the previous content.

Lesson Nav

Lesson sections