Git: Undo last commit
How to undo the last commit#
"To err is human".
One day it might so happen that you committed a bunch of files, only to realize that one or more of these files should not have been a part of the commit.
What now?
Fret not, it is pretty easy to revert a commit.
To bring back the state of the repository to the state before your last commit (used in the context of add
and commit
combination), use these two commands:
$ git reset --soft HEAD~1
$ git reset HEAD .
This will undo both the latest commit
and add
commands. The last commit
is undone by git reset --soft HEAD~1
, while git reset HEAD .
undoes the last add
.
git reset --soft HEAD~1
will undo only the last commit
, the files would still remain add
ed.If you want to do away with everything related to the last commit, use this command:
$ git reset --hard HEAD~1
This will restore the repository and the file system to the second last commit. Meaning, if new files were created in the last commit, they will also be deleted.
Tip:
--soft
- undo commit but leave the files alone--hard
- undo commit and delete the files too
Summary#
The last commit can be undone by a combination of git reset --soft HEAD~1
and git reset HEAD .
. A more destructive approach is to use git reset --hard HEAD~1
.
References#
- Git - git-reset
- Git - Reset Demystified