0

Can somebody explain why this bash script doesn't work when the if statement is in double square brackets, while without any brackets it does?

if [[ echo "word1word2" | grep -Eiq 'word1|word2' && echo "word3" | grep -Eiq 'word3' ]]
then
  echo "proceed"
else
  echo "don't proceed"
fi
LostHat
  • 33
  • 5
  • 1
    `[[` is a command, not grouping syntax. The expressions inside `[[ ... ]]` aren't arbitrary shell pipelines. – chepner Jan 04 '23 at 14:09
  • What goes inside `[[ ]]` is a *conditional expression* not a command. `ls -lt foo` will run the `ls` command with the arguments "-lt" and "foo", while `[[ ls -lt foo ]]` will check whether the value of the variable `$ls` is numerically less than ("lt") the value of the variable `$foo`. These are completely different things. – Gordon Davisson Jan 04 '23 at 16:49

1 Answers1

1

You don't need test operator at all:

if echo "word1word2" | grep -Eiq 'word1|word2' &&
   echo "word3" | grep -Eiq 'word3'
then
  echo "proceed"
else
  echo "don't proceed"
fi

It use boolean logic

If you want to use [[, then:

if [[ $(echo "word1word2" | grep -Ei 'word1|word2') && $(echo "word3" | grep -Ei 'word3') ]]
then
  echo "proceed"
else
  echo "don't proceed"
fi
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223