piotrek
piotrek

Reputation: 14540

bash: default output on empty input from pipe

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?

Upvotes: 1

Views: 919

Answers (1)

Inian
Inian

Reputation: 85590

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.

Upvotes: 3

Related Questions