Git – How to undo the last commit?

In Git, we can use git reset --soft HEAD~1 to undo the last commit in local. (The committed files haven’t pushed to the remote git server)

1. Case Study

git commit and find out some unwanted target/* files are committed accidentally, I haven’t issue the git push, any idea how to undo the commit?

Terminal

$ git commit -m "test uncommit"

[master f5f3fa6] test uncommit
 3 files changed, 3603 insertions(+)
 create mode 100644 src/main/java/com/mkyong/benchmark/BenchmarkMap.java
 create mode 100644 target/generated-sources/annotations/com/mkyong/benchmark/generated/BenchmarkForwardReverseLoop_forwardLoop_jmhTest.java
 create mode 100644 target/generated-sources/annotations/com/mkyong/benchmark/generated/BenchmarkForwardReverseLoop_jmhType.java

2. Solution

This git command git reset --soft HEAD~1 will undo the last commit, move the mistakenly committed files back to the staging area.

Terminal

$ git reset --soft HEAD~1

$ git status
On branch master
Your branch is up to date with 'origin/master'.

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        new file:   src/main/java/com/mkyong/benchmark/BenchmarkMap.java
        new file:   target/generated-sources/annotations/com/mkyong/benchmark/generated/BenchmarkForwardReverseLoop_forwardLoop_jmhTest.java
        new file:   target/generated-sources/annotations/com/mkyong/benchmark/generated/BenchmarkForwardReverseLoop_jmhType.java
       

Done.

Note
You may interest in this article : list all committed files

References

  1. Git – How to remove files from staging
  2. Git – How to list committed files that are going to push?
  3. git reset documentation

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Ram Kadwa
6 years ago

how to squash commits through command prompt