Reputation: 33
I'm looking at this code:
if diff file1 file2 > /dev/null;
then echo "same files!" `
else .....
Except isn't diff evaluated false if its output is directed to /dev/null?
Upvotes: 1
Views: 1221
Reputation: 755094
The simplest way to illustrate the difference is by example:
$ if diff file1 file2
> then echo The same
> else echo Different
> fi
2c2
< bb
---
> ee
Different
$ if diff file1 file2 > /dev/null
> then echo The same
> else echo Different
> fi
Different
$ diff -u file1 file2
--- file1 2013-09-26 19:44:06.000000000 -0700
+++ file2 2013-09-26 19:44:19.000000000 -0700
@@ -1,4 +1,4 @@
aa
-bb
+ee
cc
dd
$
Without sending the output to /dev/null
, you see both the standard output of diff
and the appropriate actions from testing the exit status of diff
. When you send the output of diff
to /dev/null
, you don't see the diff
output at all, but you do still get the appropriate action from testing the exit status of diff
. If you are writing a script, you often do not want the user to see the actual differences; it is sufficient to know that the files are different.
There are other tools that can be used for that job; in particular, cmp -s file1 file2
returns just an exit status indicating whether the files are the same or different (and it can be used on binary files, not just text files). You don't need the I/O redirection with cmp
. However, it is legitimate to use diff
and to hide the differences.
Upvotes: 4
Reputation: 50640
/dev/null
doesn't have a return value since it's not a binary that is executed. It is simply a place to redirect data when you don't care about the output.
Upvotes: 1
Reputation: 63501
No, the shell is testing against the return value of diff
, not what it wrote to the standard output. Return values are different. They are a status code returned by a program when it exits. So, it doesn't matter where you directed the output (if at all). And no /dev/null
does not have a return value. It's not a program that you run - it's just somewhere to send data that you don't want to store.
Upvotes: 3