我无法理解 git 网站上链接的书中对 git diff
命令的解释。
根据Pro Git Book , 它说
That command(
git diff
) compares what is in your working directory with what is in your staging area.
.
从我对 git 的使用来看,git diff
似乎将您的工作目录与您的存储库 进行了比较。
我有一个已提交给 repo 协议(protocol)的文件。我现在修改这个文件。在不暂存它的情况下,运行 git status 会向我显示 Changes not staged for commit 下的文件。现在,如果我运行 git diff
,我会得到 repo 和工作目录中的代码差异。我不应该没有输出,因为修改后的文件甚至没有上演吗?
我对作者试图传达的内容的理解有问题吗?
最佳答案
git diff
查看Stage和Working Directory的区别git diff --staged
查看HEAD和Stage的区别git diff HEAD
查看 HEAD 和工作目录的区别
此处 Stage
是您标记为包含在下一次提交中的更改。
Working Directory
是您正在处理和进行更改的当前目录。
HEAD
是对当前 checkout 分支中最后一次提交的引用。
尝试一次,这可能会帮助您解决问题:
假设我有一个文件 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
在文件和您的 Working Directory
中只有 Hello
,您已将其更改为 Hello World!
(您没有暂存 !
更改并不重要,它只会查找文件中的更改,无论它们是暂存的还是未暂存的)。
希望这对您有所帮助。
关于Git diff 命令文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56831893/