Git -- 撤销修改

306 阅读1分钟

重新提交

有时候我们提交完了才发现漏掉了几个文件没有添加,或者提交信息写错了。 此时,可以运行带有 --amend 选项的提交命令来重新提交:

$ git add forgotten_file
$ git commit --amend

最终你只会有一个提交 —— 第二次提交将代替第一次提交的结果。

取消暂存的文件

例如:你已经修改了两个文件并且想要将它们作为两次独立的修改提交,但是却意外地输入 git add . 暂存了它们两个。如何只取消暂存两个中的一个呢?

$ git add .
$ git status
On branch master
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        modified:   .idea/workspace.xml
        modified:   src/main/java/com/xgc/interceptor/LogInterceptor.java

我们可以看到提示我们使用git restore --staged <file>...命令来取消暂存

$ git restore --staged .idea/workspace.xml
$ git status
On branch master
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        modified:   src/main/java/com/xgc/interceptor/LogInterceptor.java

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   .idea/workspace.xml

我们可以看到文件被取消暂存了

撤销对文件的修改

当你不希望保存对文件的修改时,如何方便地撤消修改——将它还原成上次提交时的样子(或者刚克隆完的样子,或者刚把它放入工作目录时的样子)?

未暂存区域是这样:

$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   .idea/workspace.xml
        modified:   src/main/java/com/xgc/interceptor/LogInterceptor.java

我们看到提示我们使用git restore <file>...来撤销对工作区文件的修改

$ git restore src/main/java/com/xgc/interceptor/LogInterceptor.java

当我们查看文件的时候,就会发现对文件的修改撤销了

注意:这里对文件修改的撤销是不可挽回的,在使用之前请确保文件的撤销是你想要的。