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

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

    I implemented a function that returns the same results as Dennis Williamson's but uses fewer lines. It does perform a sanity check initially which causes 1..0 to fail from his tests (which I would argue should be the case) but all of his other tests pass with this code:

    #!/bin/bash
    version_compare() {
        if [[ $1 =~ ^([0-9]+\.?)+$ && $2 =~ ^([0-9]+\.?)+$ ]]; then
            local l=(${1//./ }) r=(${2//./ }) s=${#l[@]}; [[ ${#r[@]} -gt ${#l[@]} ]] && s=${#r[@]}
    
            for i in $(seq 0 $((s - 1))); do
                [[ ${l[$i]} -gt ${r[$i]} ]] && return 1
                [[ ${l[$i]} -lt ${r[$i]} ]] && return 2
            done
    
            return 0
        else
            echo "Invalid version number given"
            exit 1
        fi
    }
    

提交回复
热议问题