Skip to content
Home » How to undo the most recent commits in Git

How to undo the most recent commits in Git

Undoing a commit can be difficult if you don’t understand how it works. But once you understand, it’s actually incredibly simple. Let’s walk through the four various methods you can undo a commit.

Method 1: git reset –hard

You wish to delete commit C and never see it again, erasing all modifications made in locally changed files. Run the below code:

git reset --hard HEAD~1

Method 2 : git reset

But let’s say your most recent commit wasn’t a disaster, but just a little off. You want to undo the commit but save your changes in case you need to make any changes before committing again. Starting from here, with the most recent commit as your HEAD:

git reset HEAD~1

In above scenarios, HEAD is simply a pointer to the most recent commit. When you run git reset HEAD~1, Git moves the HEAD pointer back one commit. However, unless you use --hard, you leave your files untouched.

Method 3: git reset –soft

You can even undo your commit but keep your files and index as a last step. When you run git status, you’ll notice that the same files are still in the index. In fact, directly after this command, you could run git commit, which would redo the previous commit.

git reset --soft HEAD~1

Method 4: Undo a commit & redo

git commit -m "comment you accidentally done"
git reset HEAD~                              # (1)
[ edit files as necessary ]                
git add .                                    # (2)
git commit -c ORIG_HEAD                      # (3)
  1. Use this command to undo. It will undo your most recent commit while leaving your working tree (the current state of the files on disks) unchanged. You must add them again before you can commit them.
  2. Add anything you wish to include in your new commit with git add.
  3. Commit the modifications, using the same commit message as before. The old head was copied to .git/ORIG HEAD after a reset; commit with -c ORIG HEAD will launch an editor, which will display the log message from the previous commit and allow you to edit it. You could use the -C option if you don’t need to change the message.

To only change the Git Commit message you can use git commit --amend.

Also Read:

Configuring Git