CTO and co-founder of Signal Sciences. Author and speaker on software engineering, devops, and security.

Git Undo Last Commit

Oops, I did it again. Here's how to undo your last git commit.

If you did not git push, then you have a easy choice on how much you want to undo. If you did push, it's more work but can be done.

How do I just change the last commit message?

If you didn't push, and just need to change the last commit message, use the --amend flag.

git commit --amend -m "new commit message"

See Stack Overflow or GitHub for more details.

How do I undo the last commit and but keep the changes locally

This is useful when you forgot to add a file or what to make a few more edits. If you did not push, then this makes it so it never happened and restores everything just as if you never did a git commit in the first place.

git reset HEAD~1

Undo the commit and discard the changes

Same as above but also reverts any changes to to file as if you never did the edits at all.

git reset --hard HEAD~1

See Stack Overflow for more details.

Undo a push and the commit

The cute answer is "keep going and don't try to revert." That's not appropriate in all occasions, so if you need to undo a push and a commit, see this Stack Overflow thread.

git

© 2018 Nick Galbreath