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

前端 未结 29 1286
慢半拍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 07:06

    Here is another pure bash solution without any external calls:

    #!/bin/bash
    
    function version_compare {
    
    IFS='.' read -ra ver1 <<< "$1"
    IFS='.' read -ra ver2 <<< "$2"
    
    [[ ${#ver1[@]} -gt ${#ver2[@]} ]] && till=${#ver1[@]} || till=${#ver2[@]}
    
    for ((i=0; i<${till}; i++)); do
    
        local num1; local num2;
    
        [[ -z ${ver1[i]} ]] && num1=0 || num1=${ver1[i]}
        [[ -z ${ver2[i]} ]] && num2=0 || num2=${ver2[i]}
    
        if [[ $num1 -gt $num2 ]]; then
            echo ">"; return 0
        elif
           [[ $num1 -lt $num2 ]]; then
            echo "<"; return 0
        fi
    done
    
    echo "="; return 0
    }
    
    echo "${1} $(version_compare "${1}" "${2}") ${2}"
    

    And there is even more simple solution, if you are sure that the versions in question do not contain leading zeros after the first dot:

    #!/bin/bash
    
    function version_compare {
    
    local ver1=${1//.}
    local ver2=${2//.}
    
    
        if [[ $ver1 -gt $ver2 ]]; then
            echo ">"; return 0
        elif    
           [[ $ver1 -lt $ver2 ]]; then
            echo "<"; return 0
        fi 
    
    echo "="; return 0
    }
    
    echo "${1} $(version_compare "${1}" "${2}") ${2}"
    

    This will work for something like 1.2.3 vs 1.3.1 vs 0.9.7, but won't work with 1.2.3 vs 1.2.3.0 or 1.01.1 vs 1.1.1

提交回复
热议问题