The "opposite" of &> /dev/null
Asked Answered
L

3

6

I use the following script to compare to folders:

if diff "/home/folder1/" "/home/folder2/" &> /dev/null ; then
    echo "Files in the two folders are the same"    
else
    echo "Files in the two folders are NOT the same"
fi

Is there a brief way of explaining what the "&> /dev/null" actually does, does it return a boolean value of true/false?

And my main question: What would the opposite be? I mean, say I want the "if diff" question to be "Is the content of the two folders NOT the same?"

Leia answered 16/7, 2014 at 9:38 Comment(0)
S
9

Your &> /dev/null redirects the stdout and stderr output to /dev/null, effectively suppressing all output of the process. The exit code of the program (the numerical "result", typically stating "success" (0) or "failure" (any other number)) is not influenced by that.

To reverse the condition (the diff), just insert an exclamation mark, stating a not operator:

if ! diff "/home/folder1/" "/home/folder2/" &> /dev/null ; then
...

The diff tool always terminates with exit value 0 if (and only if) it does not find any difference. If there is a difference, 1 is the exit value; if there is trouble (I/O error or such things), 2 is the exit value. The if of the shell interprets exit values of 0 to be true and all other values to be false (mind that, because this is quite the opposite of other programming languages!).

Spigot answered 16/7, 2014 at 9:43 Comment(1)
I, personally, try to avoid those ugly ! variants and rather switch the then and the else blocks to achieve the same effect. If I have not both blocks, then I do not even use an if because I can achieve the same by using diff … && echo "then block!" or diff … || echo "else block!" (I tend to read the || in this case as otherwise). Using the redirect then makes it look like this: diff … &>/dev/null || echo "else block!" And you can use braces to group several commands, if your blocks are larger.Spigot
C
2

diff "folder1" "folder2" would return a list of differences between the two folders.

&> /dev/null redirects the stdout (all terminal output which isn't error) all stdout and stderr to a virtual device called null which discards your data.

Copolymer answered 16/7, 2014 at 9:42 Comment(1)
&> redirects both stdout and stderrHabituate
E
0

The &> redirects both normal output and errors to a file. In this case it uses the file "/dev/null" which is also called the bit bucket: it simply throws everything away. That means the output is discarded. If you don't do this your script will show the output from the commands (which you don't want to show up in the output).

See also: http://wiki.bash-hackers.org/syntax/redirection

Ennis answered 16/7, 2014 at 9:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.