I'm trying to pipe a few different commands together. some of the command may return empty output. in such case i'd like to have some default output, not the empty one. how can i achieve it in bash?
1 Answer
Just use the read command with a timeout, to see if it returns something and return some default output in cases when empty. This relies on the exit code returned by the read command on failure to read from an input stream.
.. | { read -r -t1 val || echo 'something' ; }
For example, trying to search needle in a haystack
echo haystack | grep needle | { read -r -t1 val && echo "$val" || echo 'something' ; }
The general boilerplate template for this use-case using an if condition would be something like below and more verbosely written:
if read -r -t1 val < <(echo haystack | grep needle); then
printf '%s\n' "$val"
else
printf '%s\n' "something"
fi
You could replace the part echo haystack | grep needle with the command you are tying to work with.
1 Comment
chepner
The biggest problem with this approach is that it assumes the command will produce its output within 1 second (or whatever threshold you choose). (Which is not to say there is a better approach, short of knowing more about the command involved, but it's something to be aware of.)