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:
- Why is
false
true? - Is the conditional evaluating the exit code of the command at all? I expected
0
exit code to meantrue
(the return code if thetrue
command), and any non0
exit code to meanfalse
(thefalse
command returns1
)
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.