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

前端 未结 29 1799
慢半拍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条回答
  •  猫巷女王i
    2020-11-22 07:20

    I implemented yet another comparator function. This one had two specific requirements: (i) I didn't want the function to fail by using return 1 but echo instead; (ii) as we're retrieving versions from a git repository version "1.0" should be bigger than "1.0.2", meaning that "1.0" comes from trunk.

    function version_compare {
      IFS="." read -a v_a <<< "$1"
      IFS="." read -a v_b <<< "$2"
    
      while [[ -n "$v_a" || -n "$v_b" ]]; do
        [[ -z "$v_a" || "$v_a" -gt "$v_b" ]] && echo 1 && return
        [[ -z "$v_b" || "$v_b" -gt "$v_a" ]] && echo -1 && return
    
        v_a=("${v_a[@]:1}")
        v_b=("${v_b[@]:1}")
      done
    
      echo 0
    }
    

    Feel free to comment and suggest improvements.

提交回复
热议问题