Undo a commit and redo
$ git commit -m "Something terribly misguided" # (1) $ git reset HEAD~ # (2) << edit files as necessary >> # (3) $ git add ... # (4) $ git commit -c ORIG_HEAD # (5)
- This is what you want to undo.
- This does nothing to your working tree (the state of your files on disk), but undoes the commit and leaves the changes you committed unstaged (so they'll appear as "Changes not staged for commit" in
git status, so you'll need to add them again before committing). If you only want to add more changes to the previous commit, or change the commit message1, you could use
git reset --soft HEAD~instead, which is like
git reset HEAD~2 but leaves your existing changes staged.
- Make corrections to working tree files.
git addanything that you want to include in your new commit.
- Commit the changes, reusing the old commit message.
resetcopied the old head to
-c ORIG_HEADwill open an editor, which initially contains the log message from the old commit and allows you to edit it. If you do not need to edit the message, you could use the
Beware, however, that if you have added any new changes to the index, using
commit --amend will add them to your previous commit.
If the code is already pushed to your server and you have permissions to overwrite history (rebase) then:
git push origin master --force
You can also look at this answer:
The above answer will show you
git reflog, which you can use to determine the SHA-1 for the commit to which you wish to revert. Once you have this value, use the sequence of commands as explained above.
1 Note, however, that you don't need to reset to an earlier commit if you just made a mistake in your commit message. The easier option is to
git reset (to unstage any changes you've made since) and then
git commit --amend, which will open your default commit message editor pre-populated with the last commit message.
HEAD~ is the same as
HEAD~1. Also, see What is the HEAD in git?. It's helpful if you want to uncommit multiple commits.