撤销 git add 和 git commit 操作

1. 撤销 git add

如果是撤销所有的已经add的文件:

git reset HEAD -- .

如果是撤销某个文件或文件夹:

git reset HEAD -- filename

2. 撤销 git commit

git reset --soft HEAD^

HEAD^的意思是上一个版本,也可以写成HEAD~1
如果你进行了2次commit,想都撤回,可以使用HEAD~2

其他参数解析:

  • --soft
    不删除工作空间改动代码,撤销commit,不撤销git add .

  • --mixed
    不删除工作空间改动代码,撤销commit,并且撤销git add .
    这个为默认参数, git reset --mixed HEAD^ 和 git reset HEAD^ 效果是一样的。

  • --hard
    删除工作空间改动代码,撤销commit,并且撤销git add .

补充:如果该仓库到目前为止只有commit过一次代码,则会报错:

$ git reset HEAD^
fatal: ambiguous argument 'HEAD^': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

参考文章

撤销git add - SegmentFault 思否

git使用情景2:commit之后,想撤销commit_星光的专栏-CSDN博客_git 撤销commit

原文地址:https://www.cnblogs.com/FengZeng666/p/15753153.html