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

前端 未结 29 1668
慢半拍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:19

    Here is a simple Bash function that uses no external commands. It works for version strings that have up to three numeric parts in them - less than 3 is fine as well. It can easily be extended for more. It implements =, <, <=, >, >=, and != conditions.

    #!/bin/bash
    vercmp() {
        version1=$1 version2=$2 condition=$3
    
        IFS=. v1_array=($version1) v2_array=($version2)
        v1=$((v1_array[0] * 100 + v1_array[1] * 10 + v1_array[2]))
        v2=$((v2_array[0] * 100 + v2_array[1] * 10 + v2_array[2]))
        diff=$((v2 - v1))
        [[ $condition = '='  ]] && ((diff == 0)) && return 0
        [[ $condition = '!=' ]] && ((diff != 0)) && return 0
        [[ $condition = '<'  ]] && ((diff >  0)) && return 0
        [[ $condition = '<=' ]] && ((diff >= 0)) && return 0
        [[ $condition = '>'  ]] && ((diff <  0)) && return 0
        [[ $condition = '>=' ]] && ((diff <= 0)) && return 0
        return 1
    }
    

    Here is the test:

    for tv1 in '*' 1.1.1 2.5.3 7.3.0 0.5.7 10.3.9 8.55.32 0.0.1; do
        for tv2 in 3.1.1 1.5.3 4.3.0 0.0.7 0.3.9 11.55.32 10.0.0 '*'; do
          for c in '=' '>' '<' '>=' '<=' '!='; do
            vercmp "$tv1" "$tv2" "$c" && printf '%s\n' "$tv1 $c $tv2 is true" || printf '%s\n' "$tv1 $c $tv2 is false"
          done
        done
    done
    

    A subset of the test output:

    
    
    * >= * is true
    * <= * is true
    * != * is true
    1.1.1 = 3.1.1 is false
    1.1.1 > 3.1.1 is false
    1.1.1 < 3.1.1 is true
    1.1.1 >= 3.1.1 is false
    1.1.1 <= 3.1.1 is true
    1.1.1 != 3.1.1 is true
    1.1.1 = 1.5.3 is false
    1.1.1 > 1.5.3 is false
    1.1.1 < 1.5.3 is true
    1.1.1 >= 1.5.3 is false
    1.1.1 <= 1.5.3 is true
    1.1.1 != 1.5.3 is true
    1.1.1 = 4.3.0 is false
    1.1.1 > 4.3.0 is false
    
    
    

提交回复
热议问题