Search code examples
bashunixoperatorsconditional-statementsrelational

Unix Double Test Operator and Relational Operators


In bash scripts,

if [[ $var1 != $var2 ]] 

is equivalent to the form

[ $var1 -ne $var2 ]

Why don't the relational operators (<=, >=) work inside the double test form? I tried [[ $var1 <= $var2 ]] in one of my scripts and it gives me a syntax error. Must I use the form [[ $var1 < $var2 || $var1 = $var2 ]]? Or is there something I'm missing?


Solution

  • You can use the (( )) construct:

    $ (( 4 <= 5 )) && echo ok
    ok
    $ (( 4 <= 3 )) && echo ok || echo ko
    ko
    

    or:

    var1=4
    var2=5
    if (( var1 <= var2 )) ; then
       echo ok
    fi