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

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

    I came across and solved this problem, to add an additional (and shorter and simpler) answer...

    First note, extended shell comparison failed as you may already know...

        if [[ 1.2.0 < 1.12.12 ]]; then echo true; else echo false; fi
        false
    

    Using the sort -t'.'-g (or sort -V as mentioned by kanaka) to order versions and simple bash string comparison I found a solution. The input file contains versions in columns 3 and 4 which I want to compare. This iterates through the list identifying a match or if one is greater than the other. Hope this may still help anyone looking to do this using bash as simple as possible.

    while read l
    do
        #Field 3 contains version on left to compare (change -f3 to required column).
        kf=$(echo $l | cut -d ' ' -f3)
        #Field 4 contains version on right to compare (change -f4 to required column).
        mp=$(echo $l | cut -d ' ' -f4)
    
        echo 'kf = '$kf
        echo 'mp = '$mp
    
        #To compare versions m.m.m the two can be listed and sorted with a . separator and the greater version found.
        gv=$(echo -e $kf'\n'$mp | sort -t'.' -g | tail -n 1)
    
        if [ $kf = $mp ]; then 
            echo 'Match Found: '$l
        elif [ $kf = $gv ]; then
            echo 'Karaf feature file version is greater '$l
        elif [ $mp = $gv ]; then
            echo 'Maven pom file version is greater '$l
       else
           echo 'Comparison error '$l
       fi
    done < features_and_pom_versions.tmp.txt
    

    Thanks to Barry's blog for the sort idea... ref: http://bkhome.org/blog/?viewDetailed=02199

提交回复
热议问题