DEV Community

Kenny Grant for Project Page

Posted on

How to go back to a previous commit in git

Have you ever accidentally committed the wrong files to git, but you hadn't pushed your commit up to origin yet and just want to tidy up?

All is not lost, it's quite easy to recover from this, though the commands to do so are not very intuitive. Unfortunately git doesn't have an undo command, however you can undo this quite easily using git reset.

If you want to add some files or edit the commit message, you can use git commit with the amend option:

git commit --amend

This will add whatever changes you have queued up to the previous commit (for example you may have seen a typo in your comments for the commit), and it will also let you edit the commit message for the previous commit.

If you want to get rid of the commit, while keeping the changes to your files, use git reset with HEAD~ to indicate the previous commit or a commit hash to go back to a specific commit:

git reset HEAD~

This will perform a reset of the git index (but not the changes themselves). So your files will still be as you had them, but the git index will be reset, and you can start your commit again (making modifications, not adding all the files etc). It's as if your previous commit just didn't happen.

If you committed changes that you just want to throw away, and you don't want to keep at all, you can also do a hard reset:

git reset --hard HEAD~

Or if you want to get rid of a few commits, the last commit hash you want to keep:

git reset --hard a1b2c3

But beware, this could delete or change files, and will reset the state of all the files to the previous commit, so use it with care. Usually you're better doing a soft reset.

Only ever do this if you haven't pushed the commits to origin.

If you have published the commit, you should instead publish another reverting commit, instead of rewriting history (which can cause other people lots of problems).

Top comments (0)