Search code examples
bashcomparisoncomparison-operators

Comparison operators Bash


Is it possible to collect "True or False" from a comparison in bash? Without using "if".

Example ( let me make in another language )

x = 1
y = 1
z = x == y 
print(z) #Returns true

How is it in bash if is possible?

Solved

x=1
y=1
[[ $x -eq $y ]] && z=true || z=false
echo $z #Returns true

Thanks @Viktor & @randomir


Solution

  • You can just use test, without if:

    x=1
    y=1
    [ $"{x}" -eq $"{y}" ] && echo "True" || echo "False"
    

    Here, if x equal y, logical AND (&&) works, and script echo "True".

    If x not equal, logical OR (||`) works, script echo "False".

    Upd. by @randomir advice, another available solutions:

    (( $"x" == $"y" )) && echo True || echo False
    

    Or:

    [[ $"a" == $"y" ]] && echo True || echo False