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

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

    If you have coreutils-7 (in Ubuntu Karmic but not Jaunty) then your sort command should have a -V option (version sort) which you could use to do the comparison:

    verlte() {
        [  "$1" = "`echo -e "$1\n$2" | sort -V | head -n1`" ]
    }
    
    verlt() {
        [ "$1" = "$2" ] && return 1 || verlte $1 $2
    }
    
    verlte 2.5.7 2.5.6 && echo "yes" || echo "no" # no
    verlt 2.4.10 2.4.9 && echo "yes" || echo "no" # no
    verlt 2.4.8 2.4.10 && echo "yes" || echo "no" # yes
    verlte 2.5.6 2.5.6 && echo "yes" || echo "no" # yes
    verlt 2.5.6 2.5.6 && echo "yes" || echo "no" # no
    

提交回复
热议问题