How to Undo a Git Commit

Everybody makes mistakes, and part of being a well rounded developer is understanding how to correct those mistakes. Whether the code you just committed is blatantly incorrect, or you’ve decided the additions you made are no longer necessary, it’s important to know how to undo a git commit in various circumstances.

Undo a Local Commit

If the commit hasn’t been pushed yet, we’ll be taking advantage of the git reset command. Most commonly, we can use this command to revert our most recent local commit, returning the relevant changes to being staged. From there, you can make any necessary modifications and recommit.

Bash
git reset --soft HEAD~

The --soft flag ensures we preserve the changes, but sometimes we intend to throw the commit out entirely. If you’re sure you don’t need the changes, you can switch to the --hard flag:

Bash
git reset --hard HEAD~

Undo Multiple Local Commits

Reset can also be used to undo multiple local changes at once by adding the number of commits at the end. For example, the following command will undo the last two commits and throw out the changes:

Bash
git reset --hard HEAD~2

It’s also possible to specify a particular commit hash in the command. This will revert to the given commit, undoing all commits that came afterwards:

Bash
git reset --hard ed543e12

Undo Pushed Commits

To undo a pushed git commit, we can use the git revert command to create a new commit that is the opposite of the one we want to revert.

To do this, find the commit hash using the git log command with the --oneline flag, which will return all of the most recent commits and their hashes in a compact format.

Bash
git log --oneline

Next, use this commit hash to specify which commit to undo:

Bash
git revert ed543e12

This command can also be used to revert all commits within a range. It will then record new commits that undo the changes of all commits within the range. The range is inclusive, reverting both of the specified commits along with the others within the range.

Bash
git revert ed543e12..f27b6c0b
Categories:

Leave a Reply

Your email address will not be published. Required fields are marked *