Comparing numbers in Bash

前端 未结 8 1987
栀梦
栀梦 2020-11-22 02:03

I\'m starting to learn about writing scripts for the bash terminal, but I can\'t work out how to get the comparisons to work properly. The script I\'m using is:



        
8条回答
  •  难免孤独
    2020-11-22 02:40

    The bracket stuff (e.g., [[ $a -gt $b ]] or (( $a > $b )) ) isn't enough if you want to use float numbers as well; it would report a syntax error. If you want to compare float numbers or float number to integer, you can use (( $(bc <<< "...") )).

    For example,

    a=2.00
    b=1
    
    if (( $(bc <<<"$a > $b") )); then 
        echo "a is greater than b"
    else
        echo "a is not greater than b"
    fi
    

    You can include more than one comparison in the if statement. For example,

    a=2.
    b=1
    c=1.0000
    
    if (( $(bc <<<"$b == $c && $b < $a") )); then 
        echo "b is equal to c but less than a"
    else
        echo "b is either not equal to c and/or not less than a"
    fi
    

    That's helpful if you want to check if a numeric variable (integer or not) is within a numeric range.

提交回复
热议问题