git diff
查看暂存区和工作目录之间的差异
git diff --staged
查看HEAD和暂存区之间的差异
git diff HEAD
查看HEAD和工作目录之间的差异
这里的 暂存区(Stage)
是你标记为包含在下一次提交中的更改。
工作目录(Working Directory)
是你正在工作并进行更改的当前目录。
HEAD
是指当前检出分支中最后一次提交的引用。
尝试一下这个例子,可能有助于您澄清问题:
假设我有一个文件 test.txt
,并且文件中有内容 Hello
,它当前位于我的存储库中。现在我更改了文件并添加了 World
并执行了 git status
:
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: test.txt
当我检查 git diff
时,它会显示如下内容:
--- a/test.txt
+++ b/test.txt
@@ -1 +1 @@
-Hello
+Hello World
现在,如果我将此文件暂存并检查
git status
:
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: test.txt
现在我注意到我忘记给文本添加感叹号,所以我添加了感叹号并再次检查
git status
:
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: test.txt
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: test.txt
所以您可以看到,我们在暂存和未暂存的区域中都有相同的文件。当我运行
git diff
时,它会显示如下内容:
--- a/test.txt
+++ b/test.txt
@@ -1 +1 @@
-Hello World
+Hello World!
我们已经将当前暂存区中的
Hello World
更改为
Hello World!
,因此与暂存区进行了比较。现在,如果我检查
git diff --staged
:
--- a/test.txt
+++ b/test.txt
@@ -1 +1 @@
-Hello
+Hello World
这将比较"staged"的更改和"HEAD"(最后一次提交)。由于我没有将"!"的更改放入暂存区,因此它在此处不显示。最后,当我执行"git diff HEAD"时,它将显示如下内容:
--- a/test.txt
+++ b/test.txt
@@ -1 +1 @@
-Hello
+Hello World!
在你的
工作目录
和
HEAD
(最后一次提交)之间有所改变。由于
HEAD
文件中只有
Hello
,而在
工作目录
中你已将其更改为
Hello World!
(即使你没有暂存
!
的更改,它仍会查看文件是否有更改,无论这些更改是暂存还是未暂存)。希望这能帮到你。
git diff
命令会将你的工作目录与暂存区进行比较。这意味着,如果你进行了一些更改,然后将它们添加到暂存区中,接着再次进行更改并执行git diff
命令,你将会得到这两组更改之间的差异。 - Lasse V. Karlsengit add
命令之前,索引不是空的。它填充了与您检出的提交相当的加密内容。 - ElpieKay