Redirecting output only on a successful command call
You could call the command once, redirect the output, then remove the output if there were no differences:
diff a c > output.txt && rm output.txt
diff
is a relatively expensive command, at least if the files are different. Calculating a minimal set of changes is (relatively) CPU intensive. So its understandable not to want to do that twice.
cmp
, however, is cheap, CPU-wise. Presuming these files are of a reasonable size (I doubt you'd call diff on multi-GB files), it will have almost no performance cost—and might even be quicker in the files identical case.
if ! cmp -s a c; then # -s = silent, do not print results to console
diff a c > output.txt
fi
What about temporary file?
diff a c > /tmp/output.txt
if [ $? != 0 ]; then mv /tmp/output.txt /my/folder/output.txt; else rm -f /tmp/output.txt; fi
replace the -f
with -i
if you want delete confirmation dialog.
This way you only run command twice, no temporary variables and no 'middleman' be it echo, printf or anything else.