Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

-bash: [: @: binary operator expected

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"
like image 528
zhihong Avatar asked Jan 23 '14 15:01

zhihong


2 Answers

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
like image 148
csiu Avatar answered Oct 25 '22 20:10

csiu


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
like image 4
glenn jackman Avatar answered Oct 25 '22 21:10

glenn jackman