Created
April 8, 2024 13:25
-
-
Save knu/c4db76e3cc596d788edd60dac596432d to your computer and use it in GitHub Desktop.
Comparing dot-separated version numbers in shell script (one-liners)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment