简体   繁体   English

Bash 使用 POSIX 合规性比较浮点数

[英]Bash comparing float numbers using POSIX compliance

my case is very simple:我的情况很简单:

I am trying to compare two values:我正在尝试比较两个值:

a=0.2
b=0.1

The code that I am trying to execute is:我试图执行的代码是:

if [ "$a" -gt "$b" ]; then
        echo "You are running an outdated version"
fi

Assuming you want to compare version numbers, would you please try the following:假设您要比较版本号,请尝试以下操作:

#!/bin/bash -posix

# compares version numbers
# prints 0               if $a == $b
#        positive number if $a is newer than $b
#        negative number if $a is older than $b
vercmp() {
    local a=$1
    local b=$2
    local a1=${a%%.*}           # major number of $a
    local b1=${b%%.*}           # major number of $b

    if [[ $a = "" ]]; then
        if [[ $b = "" ]]; then
            echo 0              # both $a and $b are empty
        else
            vercmp "0" "$b"
        fi
    elif [[ $b = "" ]]; then
        vercmp "$a" "0"
    elif (( 10#$a1 == 10#$b1 )); then
        local a2=${a#*.}        # numbers after the 1st dot
        if [[ $a2 = $a ]]; then
            a2=""               # no more version numbers
        fi
        local b2=${b#*.}        # numbers after the 1st dot
        if [[ $b2 = $b ]]; then
            b2=""               # no more version numbers
        fi
        vercmp "$a2" "$b2"
    else
        echo $(( 10#$a1 - 10#$b1 ))
    fi
}

Examples:例子:

vercmp 0.2 0.1
=> 1 (positive number: the former is newer)

vercmp 1.0.2 1.0.10
=> -8 (negative number: the latter is newer)

a=0.2
b=0.1
if (( $(vercmp "$a" "$b") > 0 )); then
    echo "You are running an outdated version"
fi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM