vendredi 17 septembre 2021

Confused about bash conditionals

I am confused:

echo "i-am-sure-this-is-here" > /tmp/myfile
if [[ $(grep -q sure /tmp/myfile) ]] ; then echo "Found!" ; else echo "wtf! not found" ; fi

Which gives:

wtf! not found

So I try something even simpler:

if [[ true ]] ; then echo "true -> expected" ; else echo "true -> unexpected" ; fi
if [[ false ]] ; then echo "false -> unexpected" ; else echo "false -> expected" ; fi

Which gives me something unexpected:

true -> expected
false -> unexpected

I am clearly not understanding this. Some questions:

  1. Why is false true?
  2. Is the conditional evaluating the exit code of the command at all? I expected 0 exit code to mean true (the return code if the true command), and any non 0 exit code to mean false (the false command returns 1)

How to evaluate exit codes of commands in an if-else-fi construct in bash without having to revert to explicitly comparing the exit code ($?) to an expected value, which is ugly and not very readable?

I know this would work:

grep -q sure /tmp/myfile
if [[ $? -eq 0 ]] ; then echo "Found!" ; else echo "wtf! not found" ; fi

But this is longer (2 lines instead of 1), and uglier.

Aucun commentaire:

Enregistrer un commentaire