场景

需要让暂存区的部分文件内容恢复成工作区的文件内容。

实践

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
 G:\mygitea\GitLearn\learn03   master 
$ git status
On branch master
nothing to commit, working tree clean

G:\mygitea\GitLearn\learn03   master 
$ cat readme
This is the oldest branch.
This is the older branch.
This is the young branch.
after test, update readme.

G:\mygitea\GitLearn\learn03   master 
$ cat test.txt
测试

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

G:\mygitea\GitLearn\learn03   master 
$ vim readme
This is the oldest branch.
This is the older branch.
This is the young branch.
after test, update readme.
+add something.

G:\mygitea\GitLearn\learn03   master ± 
$ git diff --cached # 由于还未提交到暂存区,因此暂存区与HEAD的文件内容一致

# 此时工作区的文件内容已经变更,与HEAD所指的commit记录的文件内容不一致了。
G:\mygitea\GitLearn\learn03   master ± 
$ git add .

G:\mygitea\GitLearn\learn03   master ± 
$ git diff --cached
diff --git a/readme b/readme
index 93d277f..99a1dfa 100644
--- a/readme
+++ b/readme
@@ -2,3 +2,4 @@ This is the oldest branch.
This is the older branch.
This is the young branch.
after test, update readme.
+add something.
diff --git a/test.txt b/test.txt
index f29dee6..f26d326 100644
--- a/test.txt
+++ b/test.txt
@@ -1 +1,2 @@
测试
+提交到暂存区

此时我们想将test.txt文件恢复回与原来工作目录内容一致:

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
# 此时将暂存区部分文件恢复成原始的内容,即与HEAD中对应文件内容一致
G:\mygitea\GitLearn\learn03   master ± 
$ git reset HEAD -- test.txt
Unstaged changes after reset:
M test.txt

G:\mygitea\GitLearn\learn03   master ± 
$ git diff --cached # 只有readme文件与HEAD不一致
diff --git a/readme b/readme
index 93d277f..99a1dfa 100644
--- a/readme
+++ b/readme
@@ -2,3 +2,4 @@ This is the oldest branch.
This is the older branch.
This is the young branch.
after test, update readme.
+add something.

# 要注意,此时只是暂存区文件内容恢复成与HEAD一致了,工作区的文件还未恢复
G:\mygitea\GitLearn\learn03   master ± 
$ cat test.txt
测试
提交到暂存区

G:\mygitea\GitLearn\learn03   master ± 
$ git checkout test.txt # 暂存区文件覆盖工作区文件
Updated 1 path from the index

G:\mygitea\GitLearn\learn03   master ± 
$ cat test.txt
测试

至此,我们就将暂存区的部分文件恢复成了原始工作目录的状态了。

总结

git reset HEAD ,是让暂存区恢复为HEAD所指向的节点,使用了该命令后,工作区修改的内容会被保留(保险),如果本地的修改需要丢弃掉,那么可使用—hard。

不过要注意,加了--hard后无法对指定的文件恢复成原始工作区文件内容,只能将暂存区所有的文件恢复成原始工作区文件内容。