How do I undo the most recent commits in Git?

2018-12-30 23:21发布

I accidentally committed the wrong files to Git, but I haven't pushed the commit to the server yet.

How can I undo those commits from the local repository?

30条回答
路过你的时光
2楼-- · 2018-12-31 00:03

I wanted to undo the lastest 5 commits in our shared repository. I looked up the revision id that I wanted to rollback to. Then I typed in the following.

prompt> git reset --hard 5a7404742c85
HEAD is now at 5a74047 Added one more page to catalogue
prompt> git push origin master --force
Total 0 (delta 0), reused 0 (delta 0)
remote: bb/acl: neoneye is allowed. accepted payload.
To git@bitbucket.org:thecompany/prometheus.git
 + 09a6480...5a74047 master -> master (forced update)
prompt>
查看更多
心情的温度
3楼-- · 2018-12-31 00:04
git rm yourfiles/*.class
git commit -a -m "deleted all class files in folder 'yourfiles'"

or

git reset --hard HEAD~1

Warning: The above command will permanently remove the modifications to the .java files (and any other files) that you wanted to commit.

The hard reset to HEAD-1 will set your working copy to the state of the commit before your wrong commit.

查看更多
旧时光的记忆
4楼-- · 2018-12-31 00:06

If you have Git Extras installed, you can run git undo to undo the latest commit. git undo 3 will undo the last 3 commits.

查看更多
浪荡孟婆
5楼-- · 2018-12-31 00:06

Use reflog to find a correct state

git reflog

reflog before REFLOG BEFORE RESET

Select the correct reflog (f3cb6e2 in my case) and type

git reset --hard f3cb6e2

After that the repo HEAD will be reset to that HEADid reset effect LOG AFTER RESET

Finally the reflog looks like the picture below

reflog after REFLOG FINAL

查看更多
荒废的爱情
6楼-- · 2018-12-31 00:07

I prefer to use git rebase -i for this job, because a nice list pops up where I can choose the commits to get rid of. It might not be as direct as some other answers here, but it just feels right.

Choose how many commits you want to list, then invoke like this (to enlist last three)

git rebase -i HEAD~3

Sample list

pick aa28ba7 Sanity check for RtmpSrv port
pick c26c541 RtmpSrv version option
pick 58d6909 Better URL decoding support

Then Git will remove commits for any line that you remove.

查看更多
时光乱了年华
7楼-- · 2018-12-31 00:08

Use git revert <commit-id>

To get the commit ID, just use git log

查看更多
登录 后发表回答