How do I undo the last commit in git?

I accidentally committed the wrong files to git.

How to undo this?

Author: Maniero, 2014-01-30

6 answers

Reset OS is recommended if the last commit has not yet been pushed to the server. Otherwise, undoing the last commit will invalidate the local copy.

If you have already pushed, it is best to "roll back" the last commit, rather than undo it. "Revert", in this context, means creating a new commit that deletes the inserted lines/introduces the deleted lines in the last commit.

git revert HEAD~1

Or HEAD~2 to reverse the last 2 commits.

Source: Git revert manpage .


If the commit has not been published, you can undo the last commit using the command git reset - see @paulomartinhago's response .

 42
Author: dcastro, 2017-04-13 12:59:42

Do the following when you delete the activities done in the stage:

git reset HEAD~1 --hard

Or to return with the activities to the stage:

git reset HEAD~1 --soft
 36
Author: paulomartinhago, 2014-01-30 11:26:09

After fixing the files run a

git add

And then do:

git commit --amend

Actually this command will redo the last commit

 8
Author: Guilherme, 2014-01-30 11:20:56

You can use this command:

git reset --soft HEAD~1
 6
Author: Miguel Bassila, 2014-01-30 11:21:15

If your last commit is the first (initial commit) run the Command git update-ref -d HEAD to retrieve the changes from your work tree and thus execute a new commit

 0
Author: Iuri Matos, 2019-05-29 11:13:13

In addition to git revert, you can use the hash of the previous commit to revert the version.

For example:

By giving a git log, you will see the last commits made and a hash identifier of the same. See:

commit c67f03af1701f5c8e47319ae5ad6fc7a2a38151f
Author: Nome <user@server>
Date:   Thu Jan 30 10:50:18 2014 -0200

Debugando

Soon, you will have to identify in the list, the commit before the one you want to undo. So just give a git checkout:

git checkout c67f03af1701f5c8e47319ae5ad6fc7a2a38151f
 -1
Author: morphinduction, 2014-01-30 13:17:00