Bash – grep – exit with 1 – if match

bashgrepshell-script

I have a bash function like so:

run_mongo(){
  mongo foo bar baz 2>&1  # send stderr to stdout
}

unfortunately this mongo command doesn't exit with 1 if there is error, so I have to match on stdout/stderr

is there some way to exit with code > 0 with grep if there is a first match? something like this:

run_mongo | grep -e "if stdout/stderr matches this we exit with 1"

I assume the way to do this would be like so:

run_mongo | grep -e "if stdout/stderr matches" | killer

where killer is a program that dies as soon as it gets its first bit of stdin.

Best Answer

Yes, you can do it with grep -vz which tells grep to find lines that don't match the pattern you give it (-v) and to read the entire ionput at once (z), so that one match means the whole thing fails:

$ printf 'foo\nbar\n' | grep -zqv foo && echo no || echo yes
yes
$ printf 'foo\nbar\n' | grep -zq foo && echo no || echo yes
no

So, in your case, something like:

run_mongo(){
  mongo foo bar baz 2>&1 | grep -vzq "whatever means failure" 
}

if run_mongo; then
 echo "Worked!"
else
  echo "Failed!"
fi

If you want to avoid reading the whole output, just use another tool. Perl, for example:

mongo foo bar baz 2>&1 | perl -ne 'exit 1 if /whatever means failure/' 
Related Question