I want to test if there is any output from the diff
(test if files are same), if none echo "Passed $x" else echo "Failed $x"
. I came up with some intermidiate step (save the output from diff to a file then read from file)
diff "./helloworld$x.out" "./output/helloworld$x.out" > tmp.txt;
output="`cat tmp.txt`";
if [ "$output" = "" ];
then
echo "Passed $x";
else
echo "Failed $x";
fi;
I'm sure the code can be improved? Main question is: is it possible to save the output from diff
directly into a variable?
This works:
If you use a variable instead of
echo
you could drop theelse
branche: set the variable to false before theif
and save 2 lines of code.If you want to actually put the result into a variable use:
Including my test to see if it does actually work:
On the
>/dev/null
part:>/dev/null 2>&1
will send output to>/dev/null
and2>&1
will send standard errors to the same file (&1
means 'use first parameter') in front of this command (so it also uses/dev/null
).sidenote:
sdiff
will show a side-by-sidediff
listings:diff
can even suppress output completely except for the "Files /bin/bash and /bin/sh differ" message using the code below.If you even want to hide that message, you've to append
> /dev/null
after the diff command to hide the output ofdiff
:/dev/null
is a special file that acts as a blackhole, if you write to it, it'll be gone, if you're reading from it, you'll get nothing back.Note that bash does not need
;
to end lines.As for the original question, to save the output of an program in a variable:
Alternative ways to check whether a variable is empty:
If you're using Bash, the last two commands are recommended for string comparison. Otherwise, the first and
[ -n "$output" ]
is recommended.a) The output of command1 can be catched with
or with backticks, but those are discouraged, because you can't nest them, and they might be hard to distinguish from apostrophs, depending on the font:
b) Instead of writing to a file, and then reading that file, (or grabbing the output, and then echoing it) you would use a pipe directly:
=>
but in your example, you're not interested in the output, but the outcome of the program - did it work?
To read about the use of && and || search for "shortcut AND and shortcut OR".
To keep the output clean, you can redirect the output of 'diff' to nowhere:
To grab success and evaluate it later, you store the result of the last command in a variable with $?:
If you want to know if two files are the same or differ (but don't care what the difference actually is),
cmp
is more suitable.