Undoing Changes
Learn about Undoing Changes
Everyone makes mistakes. Git gives you multiple ways to undo changes depending on what stage the mistake is at — working directory, staging area, or already committed. This episode covers every undo scenario, from "I just saved a bad edit" to "I need to reverse a commit that's already been pushed."
Undo Working Directory Changes
# Discard changes to a specific file (revert to last commit)
git restore index.html
# Discard ALL changes in working directory
git restore .
# Older syntax (still works)
git checkout -- index.html
Warning: These changes are gone forever. There's no undo for discarding uncommitted work.
Undo Staged Changes
# Unstage a file (keep the changes in working directory)
git restore --staged index.html
# Unstage everything
git restore --staged .
# Older syntax
git reset HEAD index.html
Undo the Last Commit
# Undo commit, keep changes STAGED
git reset --soft HEAD~1
# Undo commit, keep changes UNSTAGED (default)
git reset HEAD~1
# or explicitly:
git reset --mixed HEAD~1
# Undo commit AND discard all changes (DANGEROUS)
git reset --hard HEAD~1
Remember:
--soft— Commits are undone, changes stay staged (ready to re-commit)--mixed— Commits are undone, changes are unstaged (in working directory)--hard— Everything is gone. Use with extreme caution.
Undo Multiple Commits
# Undo the last 3 commits (keep changes staged)
git reset --soft HEAD~3
# Go back to a specific commit
git reset --hard a1b2c3d
git revert — Safe Undo for Pushed Commits
git reset rewrites history — it's dangerous for commits that have been pushed. git revert is the safe alternative: it creates a new commit that undoes the changes:
# Revert a specific commit
git revert a1b2c3d
# Revert the last commit
git revert HEAD
# Revert without auto-committing (stage the reversal for review)
git revert --no-commit a1b2c3d
Key difference:
git reset— Erases commits from history. Use only on unpushed commits.git revert— Adds a new "undo" commit. Safe for pushed/shared commits.
Recovering "Lost" Commits
If you accidentally git reset --hard and lost commits, Git keeps them for 30 days in the reflog:
# View the reflog — shows EVERYTHING you've done
git reflog
# Output:
# a1b2c3d HEAD@{0}: reset: moving to HEAD~3
# e4f5g6h HEAD@{1}: commit: Add login feature
# i7j8k9l HEAD@{2}: commit: Update styles
# Recover by resetting back to the lost commit
git reset --hard e4f5g6h
The reflog is your safety net. As long as you committed something, Git remembers it for 30 days — even if you think you deleted it.
Amending the Last Commit
# Fix the last commit message
git commit --amend -m "Corrected commit message"
# Add forgotten files to the last commit
git add forgotten-file.js
git commit --amend --no-edit
What's Next
You now know how to undo virtually anything in Git. In the next episode, we'll learn about .gitignore — telling Git which files to permanently ignore.