Undoing Mistakes Safely
💻 GitRestore files, unstage changes, amend commits and revert shared work without panic.
Almost every Git mistake is recoverable. The skill is choosing the right tool for the stage the change is in.
- 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.htmlLast 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 a1b2c3dPractice
- Make a change, stage it, unstage it and discard it.
- Amend the message of your most recent unpushed commit.
- 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
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.
Expected Output
A clean history and a revert commit that restores the previous content.
Lesson Nav
Git Course
0/9 lessons completed
- 1 Why Version Control Matters Tutorial
- 2 Your First Repository Tutorial
- 3 Staging and Committing Tutorial
- 4 History, Diffs and Logs Tutorial
- 5 Branching Tutorial
- 6 Merging and Resolving Conflicts Tutorial
- 7 Remotes and Collaboration Tutorial
- 8 Undoing Mistakes Safely Tutorial
- 9 Project: A Team Workflow Project