How to undo the most recent commits in Git?

If you accidentally committed wrong files to Git, but you don’t want to push the commit to the server yet. Don't worry, you can still undo those commits from the repo by following few steps.

 

$ 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)

 

1.       First step is for "what we want to undo"

2.      Second steps leaves working tree (the state of files on disk) unchanged but undo the commit and leaves the changes we committed (so they'll appear as "Changes not staged for commit" in git status, and add them again before committing). If other changes required into previous commit, or want to change the commit message, we could use git reset --soft HEAD~ instead, which is like git reset HEAD~ (where HEAD~is the same as HEAD~) but leaves existing changes staged.

3.      Third step is to make corrections to working tree files.

4.      git add adds anything that user want to include in new commit.

5.      Commit the changes, reusing the old commit message. reset copied the old head to .git/ORIG_HEAD; commit with -c ORIG_HEAD will open an editor, which initially contains the log message from the old commit and allows user to edit it. If we do not need to edit the message, then use the -C option.

Beware however that if you have added any new changes to the index, using commit --amend will add them to previous commit.

If the code is already pushed to a server and user have a permissions to overwrite history then:

git push origin master --force



Was this article helpful?



You are freelancing Ninja?

Try Toogit Instant Connect today, The new virtual assistant for your freelancing world.