1

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?

0

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.