bash 如何grep然后使grep的特定输出的if语句失败?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5227428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to grep and then fail an if-statement on specific output from grep?
提问by edumike
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.
好的,我需要找到命令给出的输出,特别是“gbak:ERROR”,然后失败。我不知道我是否以正确的方式处理它,如果 grep 向 /dev/null 输出,我试图使失败,但我也无法使其正常工作(可能只是语法不佳)。我确定这是一个简单的问题,请告诉我。
The if statement I've got at the moment is:
我现在得到的 if 语句是:
if [ `sudo -u firebird $GBAK_COMMAND | grep "gbak: ERROR"` == *gbak: ERROR* ]; then
echo "$DATE Unsucessful .gdb Gbak. Incorrect user/password" >> /var/log/messages
echo "Failed"
exit 1
else
echo "pass"
fi
回答by Jonathan Leffler
You don't need the 'test' operator square brackets; just test the exit status of grep:
您不需要“测试”运算符方括号;只需测试退出状态grep:
if sudo -u firebird $GBAK_COMMAND | grep -q "gbak: ERROR"
then
echo "$DATE Unsuccessful .gdb Gbak. Incorrect user/password" >> /var/log/messages
echo "Failed"
exit 1
else
echo "pass"
fi
The -qoption to grepsuppresses all output (POSIX and GNU variants) so you just get the status, which the iftests. If grepfinds the pattern, it returns success, which means that the firebirdcommand failed. The only residual issue is 'does firebirdwrite its error to standard output or to standard error?' If you need to redirect the standard error, write:
抑制所有输出(POSIX 和 GNU 变体)的-q选项,grep因此您只需获得if测试的状态。如果grep找到模式,则返回成功,这意味着firebird命令失败。唯一的遗留问题是“firebird将其错误写入标准输出还是标准错误?” 如果您需要重定向标准错误,请编写:
if sudo -u firebird $GBAK_COMMAND 2>&1 | grep -q "gbak: ERROR"
then
echo "$DATE Unsuccessful .gdb Gbak. Incorrect user/password" >> /var/log/messages
echo "Failed"
exit 1
else
echo "pass"
fi

