Search code examples
gitgit-diff

git diff does not show new file


I created a new file file.txt in my working tree. git status shows this correctly:

$ 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)

However, git diff shows nothing.

$ git diff

I found some related issues indicating the pager might be a problem, so I tried

git --no-pager diff file.txt

and

GITPAGER=cat git diff file.txt

with the same empty result.

If I add the file and then diff to HEAD, I get a correct 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

This is all on Windows 10 and the latest git version.

Why is the diff empty? Normally, I wouldn't care that much but another tool I'm using is relying on the diff output.


Solution

  • Since the new file is not tracked by git when you created it, the git had no way to identify what has changed. When you do git add file, the file moves to staging area of git and now, it is being tracked. Hence git diff will work as usual since git now has the required info about your file.

    The git docs give more info about untracked files as below -

    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.