-bash: [: @: 预期的二元运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21313130/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:20:59  来源:igfitidea点击:

-bash: [: @: binary operator expected

basherror-handling

提问by zhihong

all,

全部,

I am checking the error info in a file in the last line, I would like to have a "yes" result if there is an "Error". My shell script is like below:

我正在检查最后一行文件中的错误信息,如果出现“错误”,我希望得到“是”结果。我的 shell 脚本如下所示:

[ $(tail -1 error.log | grep -E "Error") ] && echo "yes"

then I got the error like above in the title:

然后我在标题中得到了类似上面的错误:

-bash: [: @: binary operator expected

The error message in the last line is like below:

最后一行的错误信息如下:

[aaa,bbb,ccc, Error.ddd @ ]

I think that is because of the the Error message, which has [ @ ] format content caused this error. But I do not know how to fix it. Is there any one knows how to process this [ @ ] problem. Thanks very much

我认为这是因为错误消息,其中有 [@] 格式的内容导致了这个错误。但我不知道如何解决它。有没有人知道如何处理这个[@] 问题。非常感谢

@csiu, thanks very much for your quick reply.

@csiu,非常感谢您的快速回复。

The trick here is to use double "[" as below:

这里的技巧是使用双 "[" 如下:

 [[ $(tail -1 error.log | grep -E "Error") ]] && echo "yes"

采纳答案by glenn Hymanman

Additionally to @csiu's answer, don't need the testcommand at all. You can operate based on grep's exit status:

除了@csiu 的回答之外,根本不需要该test命令。可以根据grep的退出状态进行操作:

tail -1 error.log | grep -qE "Error" && echo yes

Use -qto silence the output from grep. It's also more efficient because grep will exit immediately once the pattern is found.

用于-q使 grep 的输出静音。它也更有效,因为一旦找到模式,grep 将立即退出。



Since we only have one line of input, we don't even need grep:

由于我们只有一行输入,我们甚至不需要 grep:

[[ $(tail -1 error.log) == *Error* ]] && echo yes

回答by csiu

well since my comment works, might as well post it in the answer section ;)

好吧,既然我的评论有效,不妨将其发布在答案部分;)

Use double "[["

使用双“[[”

[[ $(tail -1 error.log | grep -E "Error") ]] && echo "yes"

Related posts:

相关文章: