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

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

    Here's a refinement of the top answer (Dennis's) that is more concise and uses a different return value scheme to make it easy to implement <= and >= with a single comparison. It also compares everything after the first character not in [0-9.] lexicographically, so 1.0rc1 < 1.0rc2.

    # Compares two tuple-based, dot-delimited version numbers a and b (possibly
    # with arbitrary string suffixes). Returns:
    # 1 if ab
    # Everything after the first character not in [0-9.] is compared
    # lexicographically using ASCII ordering if the tuple-based versions are equal.
    compare-versions() {
        if [[ $1 == $2 ]]; then
            return 2
        fi
        local IFS=.
        local i a=(${1%%[^0-9.]*}) b=(${2%%[^0-9.]*})
        local arem=${1#${1%%[^0-9.]*}} brem=${2#${2%%[^0-9.]*}}
        for ((i=0; i<${#a[@]} || i<${#b[@]}; i++)); do
            if ((10#${a[i]:-0} < 10#${b[i]:-0})); then
                return 1
            elif ((10#${a[i]:-0} > 10#${b[i]:-0})); then
                return 3
            fi
        done
        if [ "$arem" '<' "$brem" ]; then
            return 1
        elif [ "$arem" '>' "$brem" ]; then
            return 3
        fi
        return 2
    }
    

提交回复
热议问题