14.还原修改-已提交状态下

本节将学习如何撤销提交,也就是我们执行了 git commit 操作后,Git 会将我们的提交保存至版本库。

修改文件,并提交版本库

在 test 文件中添加一行 123,并保存。使用 git commit -a -m "Added 123" 命令提交至版本库。

# 查看文件内容
$ cat .\test.txt
abc
123

# 提交到版本库
$ git commit -a -m "Added 123 to the test.txt"
[master ed5fe0d] Added 123 to the test.txt
 1 file changed, 2 insertions(+), 1 deletion(-)
 
# 查看提交日志
$  git hist
* 375f4fe 2023-05-05 | Added 123 to the test.txt (HEAD -> master) [aku]
* d7f681f 2023-05-05 | Added abc to the test.txt (tag: v1) [aku]
* 01b8702 2023-05-05 | Add first file (tag: v1-beta) [aku]

还原提交

git revert 是一个用于撤销 Git 仓库中先前提交的命令。它可以创建一个新的提交,该提交撤销以前提交所做的更改。

以下是一些 git revert 命令的示例:

  • git revert HEAD: 撤销最后一次提交,并创建一个新的提交来还原更改。

  • git revert <commit>: 撤销指定提交并创建一个新的提交来还原更改。<commit> 是要撤销的提交的 SHA 值。

  • git revert -n <commit>: 在不自动提交的情况下撤销指定提交。-n--no-commit 选项告诉 Git 不要自动提交新的更改,而是等待用户手动提交更改。

请注意,在使用 git revert 命令时会创建一个新的提交,该提交将撤销以前提交所做的更改。因此,git revert 命令不会破坏 Git 仓库的历史记录,而是将其修改为包括还原更改的新提交。

# 撤销最后一次提交,并创建一个新的提交来还原更改。`--no-edit` 跳过编辑提交消息的步骤
$ git revert HEAD --no-edit
[master 6027826] Revert "Added 123 to the test.txt"

#查看日志
$ git hist
* 1ca1854 2023-05-05 | Revert "Added 123 to the test.txt" (HEAD -> master) [aku]
* 375f4fe 2023-05-05 | Added 123 to the test.txt [aku]
* d7f681f 2023-05-05 | Added abc to the test.txt (tag: v1) [aku]
* 01b8702 2023-05-05 | Add first file (tag: v1-beta) [aku]

# 查看文件
$ cat .\test.txt
abc

HEAD 是一个指针,它始终指向当前所在的本地分支的最新提交。此处也可以使用哈希值,比如 git revert ed5fe0d

Last updated