bash — boolean expression evaluation without condi

2020-04-17 08:26发布

问题:

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)?

回答1:

Instead of S=(true false), you need to create your array like this:

S=(1 0)

Then this if block:

if (( ${S[0]} || ${S[1]} ))
then
    echo "true"
else
    echo "false"
fi

will output:

true

Please note that true/false are treated as literal strings "true" and "false" in BASH.



回答2:

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 a then block if the command it calls returns 0 exit code, or on the else block otherwise. You can imitate boolean systems in bash like this though:

#!/bin/bash

true=1
false=0

A=true
B=false

# Compare by arithmetic:

if (( A || B )); then
    echo "Arithmetic condition was true."
else
    echo "Arithmetic condition was false."
fi

if (( (I > 1) == true )); then  ## Same as (( I > 1 )) actually.
    echo "Arithmetic condition was true."
else
    echo "Arithmetic condition was false."
fi

# Compare by string

if [[ $A == true || $B == true ]]; then
    echo "Conditional expression was true."
else
    echo "Conditional expression was false."
fi

# Compare by builtin command

if "$A" || "$B"; then
    echo "True concept builtin command was called."
else
    echo "False concept builtin command was called."
fi

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, and false 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.



标签: linux bash