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
You may interest in this article : list all committed files
how to squash commits through command prompt