60 Mins

7. Undoing Things — Git's Safety Net

Recovery

One of Git's most powerful features is that almost nothing is truly permanent. Deleting a file, making a bad commit, breaking the main branch — Git provides recovery mechanisms for all of these. Knowing how to undo is what separates a developer who panics from one who solves problems calmly.

Undo an Uncommitted Change

Discard changes in a file (revert to last committed version). WARNING: This permanently deletes uncommitted changes.

Bash
git restore README.md

Discard ALL uncommitted changes in the working directory:

Bash
git restore .

Remove a file from staging (unstage it, keep the changes):

Bash
git restore --staged README.md

Amend the Last Commit

Fix a typo in the last commit message:

Bash
git commit --amend -m "Correct commit message"

Add a forgotten file to the last commit. The --no-edit flag keeps the original commit message:

Bash
git add forgotten-file.js
git commit --amend --no-edit

IMPORTANT: Only amend commits that haven't been pushed yet! Amending a pushed commit rewrites history and causes problems for teammates.

git revert — The Safe Undo for Shared History

git revert creates a NEW commit that undoes a previous one. This is the safe way to undo on branches that have been pushed. First find the commit hash to undo:

Bash
git log --oneline

Revert (undo) a specific commit. Git creates a new commit (e.g., "Revert Add broken feature"). The history is preserved — the undo is itself a commit. Now push the revert to update the remote:

Bash
git revert abc1234
git push

git reset — The Powerful (Dangerous) Undo

git reset moves the branch pointer backward in history. Use ONLY on local branches that have NOT been pushed.

--soft: undo the commit, keep changes staged:

Bash
git reset --soft HEAD~1

--mixed (default): undo the commit, keep changes unstaged:

Bash
git reset HEAD~1

--hard: undo the commit AND delete all changes. WARNING: --hard permanently deletes uncommitted work.

Bash
git reset --hard HEAD~1

HEAD~1 means one commit before HEAD. HEAD~3 means three commits before HEAD.

GOLDEN RULE: Never reset commits that have been pushed to a shared branch. It rewrites history and will conflict with your teammates' local copies.

git reflog — Your Last Resort

git reflog records EVERY move of HEAD — even reset and deleted branches. It is the recovery tool for I've done something terrible.

Bash
git reflog

Recover a commit you accidentally reset, or restore your branch to that point:

Bash
git checkout def5678
# Or restore branch pointer completely:
git reset --hard def5678

Knowledge Check

Ready to test your understanding of 7. Undoing Things — Git's Safety Net?

Back