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
b are equivalent but
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?