Andrew Grimm Andrew Grimm - 9 months ago 96
Git Question

Can I use git diff on untracked files?

Is it possible to ask git diff to include untracked files in its diff output? Or is my best bet to git add the new files I've created and the existing files I have edited, and use

git diff --cached


Answer Source

With recent git versions you can git add -N the file (or --intent-to-add), which adds a zero-length blob to the index at that location. The upshot is that your "untracked" file now becomes a modification to add all the content to this zero-length file, and that shows up in the "git diff" output.

git diff

echo "this is a new file" > new.txt
git diff

git add -N new.txt
git diff
diff --git a/new.txt b/new.txt
index e69de29..3b2aed8 100644
--- a/new.txt
+++ b/new.txt
@@ -0,0 +1 @@
+this is a new file

Sadly, as pointed out, you can't git stash while you have an --intent-to-add file pending like this. Although if you need to stash, you just just add the new files and then stash. Or you can use the emulation workaround:

git update-index --add --cacheinfo \
100644 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 new.txt

(setting up an alias is your friend here).