12

Ok I need to find the output that a command gives, notely "gbak: ERROR" and then fail on it. I don't know if I'm going about it the right way, I tried to make if fail if the grep did an output to /dev/null but I couldn't get that working either (probably just poor syntax). I'm sure this is a simple one, please let me know.

The if statement I've got at the moment is:

if [ `sudo -u firebird $GBAK_COMMAND | grep "gbak: ERROR"` == *gbak: ERROR* ]; then
   echo "$DATE Unsucessful $1.gdb Gbak. Incorrect user/password" >> /var/log/messages
   echo "Failed"
   exit 1
else
   echo "pass"
fi
3

1 Answer 1

14

You don't need the 'test' operator square brackets; just test the exit status of grep:

if sudo -u firebird $GBAK_COMMAND | grep -q "gbak: ERROR"
then
   echo "$DATE Unsuccessful $1.gdb Gbak. Incorrect user/password" >> /var/log/messages
   echo "Failed"
   exit 1
else
   echo "pass"
fi

The -q option to grep suppresses all output (POSIX and GNU variants) so you just get the status, which the if tests. If grep finds the pattern, it returns success, which means that the firebird command failed. The only residual issue is 'does firebird write its error to standard output or to standard error?' If you need to redirect the standard error, write:

if sudo -u firebird $GBAK_COMMAND 2>&1 | grep -q "gbak: ERROR"
then
   echo "$DATE Unsuccessful $1.gdb Gbak. Incorrect user/password" >> /var/log/messages
   echo "Failed"
   exit 1
else
   echo "pass"
fi
Sign up to request clarification or add additional context in comments.

3 Comments

For GNU grep, you might want -q instead of/in addition to -s (GNU -s only suppresses complaints about unreadable files and such, not matched lines).
Great work, thanks! I've fixed it up now no problems. Yes very interesting, if I don't have 2>&1 there it will pass straight over it as if it's passed. I need to learn about this std error stuff as I don't know too much about it or what it does.
@Jeremiah: yes - you're right; and it is not just GNU grep but also POSIX. I'll modify the answer - thanks.

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.