Lesson 6 of 8

Undoing Things

Learn the main ways to undo changes in , from fixing your last commit message to recovering work you thought you had lost.

Bash
# Fix the last commit (message or forgotten file):
git commit --amend -m "Better message"
git add forgotten.js && git commit --amend --no-edit

# Undo a commit SAFELY — makes a new commit that reverses it:
git revert a1b2c3d

# Move back in time, keeping your files as they are:
git reset --soft HEAD~1     # undo last commit, keep changes staged

# Throw away the last commit AND its changes:
git reset --hard HEAD~1     # DESTRUCTIVE — changes are gone
Bash
# Stash — shelve uncommitted work temporarily:
git stash            # working directory is clean again
git stash pop        # bring the changes back

# Reflog — a log of every position HEAD
# has been at, even 'deleted' commits:
git reflog
# a1b2c3d HEAD@{0}: reset: moving to HEAD~1
# f4e5d6c HEAD@{1}: commit: the commit you thought you lost

git reset --hard f4e5d6c    # ...and it's back

Common question

Can I undo a mistake after committing it?

Git's undo tools differ in what they touch. restore brings back files in the working directory; reset moves the branch , and can take the staging area and working files with it; revert records a new commit that reverses an old one; and the reflog remembers every position each branch has been at, so even a bad reset can be walked back.

The rule that keeps you safe: anything committed can be recovered; anything never committed cannot. Commit early, commit often, and prefer revert over rewriting history once your work has been shared.

Source: The Git documentation describes the reflog as a record of "when the tips of branches and other references were updated in the local ", which is what lets you find work you thought was lost.

Common mix-ups

Each of these sounds reasonable. Think about why it is wrong, then open the explanation.

  • Once committed, a change is permanent, and only another commit can fix it.

  • git reset --hard is the general-purpose undo.

  • A file that was deleted and committed is gone.

Finished reading?Mark it done to track your progress.

Tip: use the ← and → keys to move between lessons.