I want to redirect the output of a command (diff
in this case) to a file but only if there is a difference in files I'm comparing. For example, imagine I have three files a
, b
, and c
where a
and b
are equivalent but a
and c
are not.
If I do diff a c > output.txt
or diff a b > output.txt
, regardless of whether there is a difference or not, output.txt
will be created. I only want output.txt
to be created if there is a diff (i.e, diff returns 1).
I'd want to do something like:
if ! diff a c > /dev/null; then
diff a c > output.txt
fi
But without running the command twice. I could save the contents of the command like so:
res=$(diff a c)
if [ $? != 0 ]; then
echo "$res" > output.txt
fi
But then I'm bringing echo
into this as a "middle-man", which could potentially raise some issues. How can I redirect output/create a file only if there's output without duplicating code?
Best Answer
You could call the command once, redirect the output, then remove the output if there were no differences: