Home > Software design >  Bourne shell multiple if conditions with grep
Bourne shell multiple if conditions with grep

Time:03-08

Using Bourne shell 4.2, I am trying to use two conditions in if statement, one of which is grep:

file=/tmp/file
cat $file
this is an error i am looking for
if [ -e "$file" ] && [ $(grep -q 'error' $file) ]; then echo "true"; else echo "false"; fi
false

I'd expect "true" to be returned here, since both conditions are true.

However, this works:

grep_count=$(grep --count 'error' /tmp/file)
if [ -e "$file" ] && [ $grep_count -gt 0 ]; then echo "true"; else echo "false"; fi
true

and lastly:

test -e /tmp/file
echo $?
0
grep -q 'error' /tmp/file
echo $?
0

What am I missing ? How can I use grep inside if statement ?

CodePudding user response:

You misused the command substitution inside the test brackets:

if [ -e "$file" ] && [ $(grep -q 'error' $file) ]; then echo "true"; else echo "false"; fi

should be write:

if [ -e "$file" ] && ( grep -q 'error' $file ); then echo "true"; else echo "false"; fi

The command substitution $(command) allows the output of a command to be substituted in place of the command name itself. So, what you did was to test the content of a null string eg:

[ "" ]

which return '1', and make your condition unsatisfied.

  • Related