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 ]];'
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.
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.
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"
${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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With