栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Bash中比较点分隔版本格式的两个字符串?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Bash中比较点分隔版本格式的两个字符串?

这是一个纯Bash版本,不需要任何外部实用程序:

#!/bin/bashvercomp () {    if [[ $1 == $2 ]]    then        return 0    fi    local IFS=.    local i ver1=($1) ver2=($2)    # fill empty fields in ver1 with zeros    for ((i=${#ver1[@]}; i<${#ver2[@]}; i++))    do        ver1[i]=0    done    for ((i=0; i<${#ver1[@]}; i++))    do        if [[ -z ${ver2[i]} ]]        then # fill empty fields in ver2 with zeros ver2[i]=0        fi        if ((10#${ver1[i]} > 10#${ver2[i]}))        then return 1        fi        if ((10#${ver1[i]} < 10#${ver2[i]}))        then return 2        fi    done    return 0}testvercomp () {    vercomp $1 $2    case $? in        0) op='=';;        1) op='>';;        2) op='<';;    esac    if [[ $op != $3 ]]    then        echo "FAIL: Expected '$3', Actual '$op', Arg1 '$1', Arg2 '$2'"    else        echo "Pass: '$1 $op $2'"    fi}# Run tests# argument table format:# testarg1   testarg2     expected_relationshipecho "The following tests should pass"while read -r testdo    testvercomp $testdone << EOF1 1 =2.1          2.2          <3.0.4.10     3.0.4.2      >4.08         4.08.01      <3.2.1.9.8144 3.2          >3.2          3.2.1.9.8144 <1.2          2.1          <2.1          1.2          >5.6.7        5.6.7        =1.01.1       1.1.1        =1.1.1        1.01.1       =1 1.0          =1.0          1 =1.0.2.0      1.0.2        =1..0         1.0          =1.0          1..0         =EOFecho "The following test should fail (test the tester)"testvercomp 1 1 '>'

运行测试:

$ . ./vercompThe following tests should passPass: '1 = 1'Pass: '2.1 < 2.2'Pass: '3.0.4.10 > 3.0.4.2'Pass: '4.08 < 4.08.01'Pass: '3.2.1.9.8144 > 3.2'Pass: '3.2 < 3.2.1.9.8144'Pass: '1.2 < 2.1'Pass: '2.1 > 1.2'Pass: '5.6.7 = 5.6.7'Pass: '1.01.1 = 1.1.1'Pass: '1.1.1 = 1.01.1'Pass: '1 = 1.0'Pass: '1.0 = 1'Pass: '1.0.2.0 = 1.0.2'Pass: '1..0 = 1.0'Pass: '1.0 = 1..0'The following test should fail (test the tester)FAIL: Expected '>', Actual '=', Arg1 '1', Arg2 '1'


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/405520.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号