如何grep,然后使grep的特定输出的if语句失败? [英] How to grep and then fail an if-statement on specific output from grep?

查看:102
本文介绍了如何grep,然后使grep的特定输出的if语句失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我需要找到命令给出的输出,请注意 gbak:ERROR,然后失败。我不知道我是否要按照正确的方式进行操作,如果grep对/ dev / null进行了输出,我试图使它失败,但是我也无法使它工作(可能只是语法很差)。我确信这是一个简单的例子,请让我知道。

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.

我目前所拥有的if语句是:

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


推荐答案

您不需要'test'运算符;只需测试 grep 的退出状态:

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

grep -q 选项禁止显示所有输出(POSIX和GNU变体),因此只需获取状态,即可通过 if 测试。如果 grep 找到了模式,则返回成功,这意味着 firebird 命令失败。唯一的残留问题是 firebird 是否将其错误写到标准输出或标准错误?如果需要重定向标准错误,请写:

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

这篇关于如何grep,然后使grep的特定输出的if语句失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆