-bash: [: @: binary operator expected

爷,独闯天下 提交于 2020-07-18 16:27:28

问题


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:

[ $(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.

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

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

回答1:


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

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

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


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

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



回答2:


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:

  • How to use double or single bracket, parentheses, curly braces
  • Meaning of double square brackets in bash


来源:https://stackoverflow.com/questions/21313130/bash-binary-operator-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!