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

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

    How about this? Seems to work?

    checkVersion() {
    subVer1=$1
    subVer2=$2
    
    [ "$subVer1" == "$subVer2" ] && echo "Version is same"
    echo "Version 1 is $subVer1"
    testVer1=$subVer1
    echo "Test version 1 is $testVer1"
    x=0
    while [[ $testVer1 != "" ]]
    do
      ((x++))
      testVer1=`echo $subVer1|cut -d "." -f $x`
      echo "testVer1 now is $testVer1"
      testVer2=`echo $subVer2|cut -d "." -f $x`
      echo "testVer2 now is $testVer2"
      if [[ $testVer1 -gt $testVer2 ]]
      then
        echo "$ver1 is greater than $ver2"
        break
      elif [[ "$testVer2" -gt "$testVer1" ]]
      then
        echo "$ver2 is greater than $ver1"
        break
      fi
      echo "This is the sub verion for first value $testVer1"
      echo "This is the sub verion for second value $testVer2"
    done
    }
    
    ver1=$1
    ver2=$2
    checkVersion "$ver1" "$ver2"
    

提交回复
热议问题