5

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"
zhihong
  • 1,808
  • 2
  • 24
  • 34
  • `[ ]` is to do some comparison and you are just giving one piece of text, so for bash `[ @ ]` is not something it can interpret. – fedorqui Jan 23 '14 at 15:56
  • what about using double "[" and "]"? `[[ $(tail -1 error.log | grep -E "Error") ]] && echo "yes"` – csiu Jan 23 '14 at 15:57
  • @fedorqui, I think grep -E is for comparison. – zhihong Jan 23 '14 at 16:02
  • 1
    `-E` instructs `grep` to use extended regular expressions; it's unnecessary here since `Error` has the same meaning whether it is interpreted as a basic or extended regular expression. – chepner Jan 23 '14 at 16:16

2 Answers2

5

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:

Community
  • 1
  • 1
csiu
  • 3,159
  • 2
  • 24
  • 26
4

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
glenn jackman
  • 238,783
  • 38
  • 220
  • 352