Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditional binary operator expected in shell script

Tags:

I was trying a simple program to compare the string values stored on a log file and was getting an error as below,

#!/bin/bash  check_val1="successful" check_val2="completed" log="/compile.log"  if [[ grep $check_val1 $log -ne $check_val1 || grep $check_val2 $log -ne $check_val2 ]]; then         echo "No Error" else         echo "Error" fi   Error:  ./simple.sh: line 7: conditional binary operator expected ./simple.sh: line 7: syntax error near `$check_val1' ./simple.sh: line 7: `if [[ grep $check_val1 $log -ne $check_val1 || grep $check_val2 $log -ne $check_val2 ]];' 
like image 889
Angus Avatar asked Aug 04 '14 12:08

Angus


People also ask

Can I use != In bash?

To check if two strings are equal in bash scripting, use bash if statement and double equal to== operator. To check if two strings are not equal in bash scripting, use bash if statement and not equal to!= operator.

What does != Mean in shell script?

And the != operator means 'is not equal to', so [ $? != 0 ] is checking to see if $? is not equal to zero. Putting all that together, the above code checks to see if the grep found a match or not.

How do you check if a variable is defined in bash?

To find out if a bash variable is defined: Return true if a bash variable is unset or set to the empty string: if [ -z ${my_variable+x} ]; Also try: [ -z ${my_bash_var+y} ] && echo "\$my_bash_var not defined"

What is ${ 0 * in shell script?

${0} is the first argument of the script, i.e. the script name or path. If you launch your script as path/to/script.sh , then ${0} will be exactly that string: path/to/script.sh . The %/* part modifies the value of ${0} . It means: take all characters until / followed by a file name.


1 Answers

Problem is in your if [[...]] expression where you are using 2 grep commands without using command substitution i.e. $(grep 'pattern' file).

However instead of:

if [[ grep $check_val1 $log -ne $check_val1 || grep $check_val2 $log -ne $check_val2 ]]; then 

You can use grep -q:

if grep -q -e "$check_val1" -e "$check_val2" "$log"; then 

As per man grep:

-q, --quiet, --silent          Quiet mode: suppress normal output.  grep will only search a file until a match           has been found, making searches potentially less expensive. 
like image 192
anubhava Avatar answered Nov 13 '22 14:11

anubhava