Diff Tool – How to Print Full File Diff When File is Missing

diff()

I'm trying to compare files on the root file system with a backup, and I'd like the comparison to work a bit like git or svn diff when a file has been added or removed – That is, display the full file diff. diff unfortunately just prints a No such file or directory message, which is not very useful. I couldn't find an option for this.

The simplest workaround I could find is to parse the diff output and diff -u path <(printf '') or diff -u <(printf '') path depending on which path exists. That's a bit of a kludge – Probably 10 lines of code for what could be a simple diff option.

Another workaround is

diff -u <([ -e "$path1" ] && cat "$path1") <([ -e "$path2" ] && cat "$path2")

, but that loses the file names in the diff.

Based on Craig Sanders's answer and the previous workaround, I ended up with this:

diff -u \
    "$([ -e "$path1" ] && echo "$path1" || echo /dev/null)" \
    "$([ -e "$path2" ] && echo "$path2" || echo /dev/null)"

Edit: Turns out there is an option for it:

-N, --new-file
       treat absent files as empty

In other words:

diff -Nu "$path1" "$path2"

Best Answer

With at least some versions of GNU diffutils' diff, you can use the -N flag to do that directly (although the documentation appears to say that only works for directory diffs).

$ ls
foo
$ cat foo
foo
$ diff -u foo bar
diff: bar: No such file or directory
$ diff -uN bar foo
--- bar 1970-01-01 01:00:00.000000000 +0100
+++ foo 2012-09-04 12:45:34.000000000 +0200
@@ -0,0 +1 @@
+foo
$ diff -uN foo bar
--- foo 2012-09-04 12:45:34.000000000 +0200
+++ bar 1970-01-01 01:00:00.000000000 +0100
@@ -1 +0,0 @@
-foo
$ diff -v
diff (GNU diffutils) 2.8.1
Copyright (C) 2002 Free Software Foundation, Inc.
Related Question