git diff 不显示新文件

git diff does not show new file

我在我的工作树中创建了一个新文件 file.txtgit status 正确显示:

$ git status
On branch mybranch
Untracked files:
  (use "git add <file>..." to include in what will be committed)

        file.txt

nothing added to commit but untracked files present (use "git add" to track)

然而,git diff 什么也没显示。

$ git diff

我发现了一些相关问题,表明寻呼机可能有问题,所以我尝试了

git --no-pager diff file.txt

GITPAGER=cat git diff file.txt

相同的空结果。

如果我添加文件然后将 diff 到 HEAD,我会得到正确的 diff。

$ git add file.txt
$ git diff --cached
diff --git a/file.txt b/file.txt
new file mode 100644
index 0000000..f2d7933
--- /dev/null
+++ b/file.txt
@@ -0,0 +1 @@
+asds
\ No newline at end of file

这一切都在 Windows 10 和最新的 git 版本上。

为什么 diff 是空的? 通常,我不会那么在意,但我正在使用的另一个工具依赖于 diff 输出。

由于新文件在您创建时未被 git 跟踪,因此 git 无法识别更改的内容。当您执行 git add file 时,文件将移动到 git 的暂存区,现在它正在被跟踪。因此 git diff 将照常工作,因为 git 现在有关于您的文件的所需信息。

git docs 提供了有关未跟踪文件的更多信息,如下所示 -

Remember that each file in your working directory can be in one of two states: tracked or untracked. Tracked files are files that were in the last snapshot; they can be unmodified, modified, or staged. In short, tracked files are files that Git knows about.

Untracked files are everything else — any files in your working directory that were not in your last snapshot and are not in your staging area. When you first clone a repository, all of your files will be tracked and unmodified because Git just checked them out and you haven’t edited anything.

As you edit files, Git sees them as modified, because you’ve changed them since your last commit. As you work, you selectively stage these modified files and then commit all those staged changes, and the cycle repeats.