34

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 ]];'
1
  • Just curious -- Is there a way to use the [[ ... ]] but still make it work? Commented Aug 13, 2023 at 19:42

2 Answers 2

40

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.
Sign up to request clarification or add additional context in comments.

11 Comments

I executed like this on the shell grep -q -e "success" -e "leaving" compile.log > a cat a => was not listing any vlaue
grep -q doesn't print anything on stdout. It just returns success/fail return value. If you remove -q then it will print values.
The log file contains the string "success" and "leaving".[root@a a~]# grep -e "success" -e "leaving" compile.log [root@aa~]# grep -e "success" -e "leaving" compile.log > a [root@aa~]# cat a [root@aa ~]# grep -e "suess" -e "leang" compile.log > a [root@aa ~]# cat a
You can do: grep -iq -e "SUCCESS" -e "Leaving" "compile.log" for that case.
-e for the patern and -i to ignore the case. Thanks anubhava.
|
21

[[ triggers the test command. Test doesn't support testing the exit status of a command just by typing the command

2 Comments

How would you fix it?
I came here to look for; briefly what brackets mean. Thanks.

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.