I tried to play around with bash, and even tried documentation and few threads though I cannot seem to get it right.
S=(true false)
if (( ${S[0]} || ${S[1]} ))
then
echo "true"
else
echo "false"
fi
- how can the boolean expression be evaluated under bash? (any chance to fix the snippet above?)
- is there any possibility to evaluate it without
if
, i.e. assign it to a variable directly (no if manipulation)?
Instead of
S=(true false)
, you need to create your array like this:Then this if block:
will output:
true
Please note that true/false are treated as literal strings "true" and "false" in BASH.
There isn't really such a thing as boolean in bash, only integral arithmetic expressions e.g. (( n )), which would return an exit code of 0 (no error or no failure code) if its value is greater than 1, or a nonzero code (has error code) if it evaluates to 0.
if
statements execute athen
block if the command it calls returns 0 exit code, or on theelse
block otherwise. You can imitate boolean systems in bash like this though:And I prefer the string comparison since it's a less hacky approach despite probably being a bit slower. But I could use the other methods too if I want too.
(( ))
,[[ ]]
,true
, andfalse
all are just builtin commands or expressions that return an exit code. It's better that you just think of the like that than thinking that they are really part of the shell's main syntax.