6

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"
4
  • [ ] is to do some comparison and you are just giving one piece of text, so for bash [ @ ] is not something it can interpret. Commented Jan 23, 2014 at 15:56
  • what about using double "[" and "]"? [[ $(tail -1 error.log | grep -E "Error") ]] && echo "yes" Commented Jan 23, 2014 at 15:57
  • @fedorqui, I think grep -E is for comparison. Commented Jan 23, 2014 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. Commented Jan 23, 2014 at 16:16

2 Answers 2

6

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:

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

In hindsight, efficiency is not relevant since we only have one line of input
@ glenn, great, that is my original idea, to hide the output of grep. but do not know "-q" option here. Thanks a lot~

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.