How do I undo my most recent local commits in Git?

Did you accidentally commit a whole bunch of files in Git, but - thankfully - haven’t pushed that commit to remote, and want to undo it? I'll show you a couple ways you can fix it (one-liners!).

Let’s say you committed some faulty code:

git add .
git commit -m "bug fix!"  # didn’t mean to commit! 🥴 oops!

Luckily, if you haven’t pushed it upstream yet, you have a couple options (besides not making mistakes, good luck with that) to help undo that situation.

We’ll go over some of the simpler options I prefer to use to undo accidental commits.

Git Reset

There are a few one-liners you can use with git reset to undo your last commit, depending on your goals.

# Undo your commit but keep the changes staged:
git reset --soft HEAD~

# Undo your commit and unstage the changes
# but keep them in your working directory:
git reset HEAD~

# Completely discard any changes to the last commit:
git reset --hard HEAD~  # ⚠️ destructive!

Git Restore

If you have a version of Git newer than 2.23 (type git --version in your terminal if you’re unsure), you can use the git restore command to go back to the changes from your last commit:

git restore --source HEAD~ .  # there’s dot at the end!

Note: using git restore won’t alter your git history.

*If you’re confused about the syntax ... HEAD~, HEAD is referencing the currently checked-out commit and the tilde ~ is saying go back n commits (and chooses the first parent for merge commits). If you don’t specify a number after the tilde, it represents going back one commit.

Some differences between reset and restore

The difference between git reset and git restore is that restore "restores" files in your working directory or index without affecting history; while reset moves the HEAD and changes the commit history.


Useful Links