Skip to content

Instantly share code, notes, and snippets.

@knu
Created April 8, 2024 13:25
Show Gist options
  • Select an option

  • Save knu/c4db76e3cc596d788edd60dac596432d to your computer and use it in GitHub Desktop.

Select an option

Save knu/c4db76e3cc596d788edd60dac596432d to your computer and use it in GitHub Desktop.

Revisions

  1. knu created this gist Apr 8, 2024.
    32 changes: 32 additions & 0 deletions comparing_dot-separated_version_numbers.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    # Comparing dot-separated version numbers in one line

    # How to say $a >= $b using various tools and languages?
    a=1.10.0
    b=1.9.5

    set -e

    # POSIX
    [ "$({ echo $a; echo $b; } | sort -n -t. -k1,1 -k2,2 -k3,3 | tail -n1)" = "$a" ]

    # GNU sort
    [ "$({ echo $a; echo $b; } | sort -V | tail -n1)" = "$a" ]

    # awk
    { echo $a; echo $b; } | awk -F. '{for(i=1;i<=NF;i++)v[NR]=v[NR]sprintf("%05d",$i)}END{exit!(v[1]>=v[2])}'

    # Perl
    perl -Mversion -e '($a,$b)=map{qv("v$_")}@ARGV;exit(!($a>=$b))' "$a" "$b"

    # Ruby
    ruby -e 'a,b=$*.map{Gem::Version.new(_1)};exit(a>=b)' "$a" "$b"
    ruby -e 'exit($*.map{Gem::Version.new(_1)}.reduce(:>=))' "$a" "$b"
    # Ruby >=3.1
    ruby -e 'a,b=$*;exit(Gem::Version.new(a)>=b)' "$a" "$b"

    # jq
    echo "$a $b" | jq -eR 'split(" ")|map(split(".")|map(tonumber))|.[0]>=.[1]' >/dev/null
    jq --arg a "$a" --arg b "$b" -en '[$a,$b]|map(split(".")|map(tonumber))|.[0]>=.[1]' >/dev/null

    # dpkg (Debian/Ubuntu)
    dpkg --compare-versions "$a" ge "$b"