场景

将仓库中工作目录文件修改后提交到了暂存区,此时继续修改工作目录文件,修改后发现使用暂存区的代码更好,此时希望将暂存区文件代码恢复到工作目录来。

实践

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
 G:\mygitea\GitLearn\learn03   master ± 
$ git status
On branch master
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
modified: test.txt

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: test.txt


G:\mygitea\GitLearn\learn03   master ± 
$ git diff --cached
diff --git a/test.txt b/test.txt
index f29dee6..f26d326 100644
--- a/test.txt
+++ b/test.txt
@@ -1 +1,2 @@
测试
+提交到暂存区

G:\mygitea\GitLearn\learn03   master ± 
$ git diff
diff --git a/test.txt b/test.txt
index f26d326..e3aa423 100644
--- a/test.txt
+++ b/test.txt
@@ -1,2 +1,3 @@
测试
提交到暂存区
+提交后对工作区进行变更.

此时要修改工作区的内容使其与暂存区内容一致,我们使用git checkout命令。如果要改暂存区的内容,我们使用git reset命令。

1
2
3
4
5
6
7
8
9
10
 G:\mygitea\GitLearn\learn03   master ± 
$ git checkout -- test.txt

G:\mygitea\GitLearn\learn03   master ± 
$ git diff

G:\mygitea\GitLearn\learn03   master ± 
$ cat test.txt
测试
提交到暂存区

执行命令后,工作区恢复成与暂存内容一致。

总结

以暂存区为中心:

  • 暂存区与HEAD比较:git diff —cached
  • 暂存区与工作区比较: git diff
  • 暂存区恢复成HEAD : git reset HEAD
  • 暂存区覆盖工作区修改:git checkout

小tips:Git 2.23之后用git switch和git restore来替代git checkout功能,git switch替换git checkout切换分支的功能,git restore替换对工作区文件进行回复的功能。

Q1:未执行git add之前, 暂存区的内容是什么?

未执行git add之前就是 HEAD 对应的内容,或分支最新commit的内容