How to compare two strings in dot separated version format in Bash?

前端 未结 29 1639
慢半拍i
慢半拍i 2020-11-22 06:52

Is there any way to compare such strings on bash, e.g.: 2.4.5 and 2.8 and 2.4.5.1?

29条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 06:57

    Here's another pure bash version, rather smaller than the accepted answer. It only checks whether a version is less than or equal to a "minimum version", and it will check alphanumeric sequences lexicographically, which often gives the wrong result ("snapshot" is not later than "release", to give a common example). It will work fine for major/minor.

    is_number() {
        case "$BASH_VERSION" in
            3.1.*)
                PATTERN='\^\[0-9\]+\$'
                ;;
            *)
                PATTERN='^[0-9]+$'
                ;;
        esac
    
        [[ "$1" =~ $PATTERN ]]
    }
    
    min_version() {
        if [[ $# != 2 ]]
        then
            echo "Usage: min_version current minimum"
            return
        fi
    
        A="${1%%.*}"
        B="${2%%.*}"
    
        if [[ "$A" != "$1" && "$B" != "$2" && "$A" == "$B" ]]
        then
            min_version "${1#*.}" "${2#*.}"
        else
            if is_number "$A" && is_number "$B"
            then
                [[ "$A" -ge "$B" ]]
            else
                [[ ! "$A" < "$B" ]]
            fi
        fi
    }
    

提交回复
热议问题