How to compare version string in a better way from shell command line

November 5, 2019

In shell script, we ofter need to compare version strings to carry out different actions for different versions. one of the solution would be use bc or test:

echo "2.0 < 3.0" | bc

but sometimes version string will not be pure number, it could be:

2.0-alpha 2.0-beta 2.9a 3.0.1 3.0.1-rc1

on stackoverflow, there comes a better solution. the original post is:https://stackoverflow.com/questions/16989598/bash-comparing-version-numbers/24067243 it use sort -V or gawk to get a better compare. these two solutions both has pro and cons. based on the sort -V solution, I refined my tmux.conf, since the tmux version comes to 2.9a.

run-shell "tmux setenv -g TMUX_VERSION $(tmux -V | cut -c 6-)"
run-shell 'tmux setenv -g TMUX_VERSION_GE_2_1 $(test "$(printf "%s\n" $TMUX_VERSION 2.1|sort -V|head -n 1)" != "2.1";echo $?)'
run-shell 'tmux setenv -g TMUX_VERSION_GE_2_2 $(test "$(printf "%s\n" $TMUX_VERSION 2.2|sort -V|head -n 1)" != "2.2";echo $?)'
run-shell 'tmux setenv -g TMUX_VERSION_GE_2_4 $(test "$(printf "%s\n" $TMUX_VERSION 2.4|sort -V|head -n 1)" != "2.4";echo $?)'
run-shell 'tmux setenv -g TMUX_VERSION_GE_3_0 $(test "$(printf "%s\n" $TMUX_VERSION 3.0|sort -V|head -n 1)" != "3.0";echo $?)'
Nifty tech tag lists fromĀ Wouter Beeftink