echo stdin, unless empty, in which case cat a file
The pipeline fstdraw in.fst | dot -Tpng | convert - -rotate 90 out.png
converts a file in a certain binary format into a PNG image.
Unfortunately, in some cases fstdraw
emits zero bytes. (A bug in its package, OpenFst.) Then dot
too emits zero bytes instead of a PNG, whereupon convert
fails to create out.png
. That missing file then breaks later commands.
At the first pipe symbol, how can one insert something that means echo my input, but if my input is empty, instead output the file dummy.txt, so out.png
is always created?
(One could write a script, but surely some shell builtin or standard tool does this already.)
Something like fstdraw in.fst | cat_maybe dummy.txt | dot ...
Solution 1:
Explicit answer
The package moreutils
provides ifne
tool. Normally it runs the given command if and only if the standard input is not empty. It has, however, a reverse operation mode:
-n
Reverse operation. Run the command if the standard input is empty.
Note that if the standard input is not empty, it is passed through
ifne
in this case.
So the solution is:
fstdraw in.fst | ifne -n cat dummy.txt | dot -Tpng | convert - -rotate 90 out.png
Alternative approach
This was posted originally as a comment. The point is to detect when convert
fails and act accordingly. The method doesn't answer the explicit question, yet it may solve your specific problem. I'm posting it here for educational purpose.
fstdraw in.fst | dot -Tpng | convert - -rotate 90 out.png || cp dummy.png out.png