Last Updated: March 03, 2016
·
3.55K
· zedtux

Bash: String version comparaison

While I was writing a shell script in bash I have the case where I should generate a path based on the kernel version of the current machine.

My need is the following:

  • If the kernel version is lower than 3.7.0 then return 3.6
  • If the kernel version is >= 3.7.0 and < 3.8.0 return 3.7
  • If the kernel version is >= 3.8.0 and < 3.9.0 return 3.8
  • If the kernel version is >= 3.9.0 return 3.9

I found an answer on Stackoverflow (http://stackoverflow.com/a/4024263/1996540) but this wasn't working all the time.
After having understood how it is working I have updated the code and now got something working perfectly!

I'm then sharing it to the world :)

verlte() {
    [ "$1" = "$2" ] && return 1 || [  "$2" = "`echo -e "$1\n$2" | sort -V | head -n1`" ]
}

verlt() {
    [ "$1" = "$2" ] && return 1 || verlte $2 $1
}

check_version()
{
    verlt $CURRENT_KERNEL_VERSION_SHORT 3.7.0 && echo "Kernel version $CURRENT_KERNEL_VERSION_SHORT is < 3.7.0"
    [[ "$CURRENT_KERNEL_VERSION_SHORT" == 3.7.* ]] && echo "Kernel version $CURRENT_KERNEL_VERSION_SHORT is ~> 3.7.0"
    [[ "$CURRENT_KERNEL_VERSION_SHORT" == 3.8.* ]] && echo "Kernel version $CURRENT_KERNEL_VERSION_SHORT is ~> 3.8.0"
    verlte $CURRENT_KERNEL_VERSION_SHORT 3.9.0 && echo "Kernel version $CURRENT_KERNEL_VERSION_SHORT is > 3.9.0"
}

Let's now test it a bit:

CURRENT_KERNEL_VERSION_SHORT="3.6.9" && check_version
#=> Kernel version 3.6.9 is < 3.7.0
CURRENT_KERNEL_VERSION_SHORT="3.7.0" && check_version
#=> Kernel version 3.7.0 is ~> 3.7.0
CURRENT_KERNEL_VERSION_SHORT="3.8.1" && check_version
#=> Kernel version 3.8.1 is ~> 3.8.0
CURRENT_KERNEL_VERSION_SHORT="3.9.5" && check_version
#=> Kernel version 3.9.5 is > 3.9.0
CURRENT_KERNEL_VERSION_SHORT="3.10.1" && check_version
#=> Kernel version 3.10.1 is > 3.9.0