The aim is to not even start $foo if there is no input.
This can be useful if foo=”diff – xyz”, and the input is missing or empty.
Otherwise, diff would output all of “xyz” as the difference.
The original problem is that “cat doesnotexist | diff – exists” outputs the content of “exists” (prefixed with “>”), while I want the entire pipe to fail.
My current solution is:
cat doesnotexist | (read first|| exit 1; (echo "$first"; cat) | diff - exists)
, but I would like a shorter one.
I removed the pipe, it has no added value in your example. Strictly, this doesn’t let the diff fail, it’s just not executed.