Grep error without error message

I have a (long) Bash script that does something like this:

set -o nounset
set -o errexit
set -o pipefail

echo -e "foo \n bar" | grep "baz" | tr -d ' '

echo "here"

The script crashes without an error message because the grep command returns error 1 without printing an error message.

How to make my script reliable?

+4
source share
2 answers

grepwill generate a non-zero exit code if the template does not match. Moreover, he did not give any error messages. To get an error message if the template is not found at the input, you will need an alternative. You can use awk:

echo -e "foo \n bar" | \
awk 'BEGIN{f=0}/baz/{f=1;print;}END{if (!f) {print "Error; string not found"; exit 1;}}' | \
tr -d ' '

This will be very similar grep(in terms of exit code) and will generate an error message if no match is found.

STDERR, :

echo -e "foo \n bar" | \
awk 'BEGIN{f=0}/baz/{f=1;print;}END{if (!f) {print "Error; string not found" > "/dev/stderr"; exit 1;}}' | \
tr -d ' '
+1

grep -q :

if $(echo -e "foo \n bar" | grep -q "baz"); then
    echo "grep success"
else
    echo "grep failure"
fi
+1

Source: https://habr.com/ru/post/1527685/


All Articles