1

With a bash script, I want to take action if the node version is less than a particular value.

How can I compare semver versions with Bash?

something like:

NV=$(node --version)

if [[ ${NV} < 5 ]]; then 
   # do something
fi

obvious that's not quite right

node --version output just looks like:

$ node --version
v6.9.5
Alexander Mills
  • 90,741
  • 139
  • 482
  • 817

2 Answers2

3

you can use sort -V for comparing versions as stated in this post. a very nice oneliner.

or if you don't mind taking advantage of debian distributions (i'm assuming this premise here), you can:

$ dpkg --compare-versions $(node --version | grep -Eo "([0-9]\.)+[0-9]+") lt 5
$ echo $?
$ 1
Community
  • 1
  • 1
odradek
  • 993
  • 7
  • 14
1

If all you need to do is compare the first digit, you could do this :

nv=$(node --version)
if [[ $nv =~ ^v([0-9]+) ]] && (( ${BASH_REMATCH[1]} > 5 )) ; then 
   # do something
fi

This code uses the =~ regex matching operator to match any sequence of numbers following a leading "v", the parentheses allowing the digit sequence to be saved in a sub-expression, and then performing a numerical comparison on that saved sub-expression (found in the BASH_REMATCH array at index 1).

Please note that it is generally recommended (though not strictly required) to have variables other than environment variables be lowercase.

Fred
  • 6,590
  • 9
  • 20