Bash: Convert a string (version number) to an integer

bashshell-script

I want to get the version of glibc and use it in an if statement stating if glibc is less than 2.15 then.

However the issue is that when using the ldd –version this is output as a string. i need to convert it in to an integer to do the less than comparison.

Previously I have done it this way

if [ "$(ldd --version | sed -n '1 p' | tr -cd '[:digit:]' | tail -c 3)" -lt 215 ]; then

This is not really very good as I have to remove the decimal point and cannot give a true version number comparison. The other issue is that some versions of glibc have multiple decimal points (seen here https://en.wikipedia.org/wiki/GNU_C_Library#Version_history) which would mean my existing comparison would mess up.

So to that end I would need to be able to convert the glibc version intact to an integer and correctly compare the version numbers even with multiple decimal points.

Any ideas? Thanks

Best Answer

ldd --version | sed 's/.* //;q' | awk -F. '{ if ($1 > 2 || ($1 == 2 && $2 >= 15)) { exit 0 } else {exit 1} }'

Explanation:

The sed command takes the first line of output from ldd --version, strips out everything up to and including the last space, and then quits (so it only prints the number).

The -F flag to awk sets . as the field separator.

If the first number (before the dot) is greater than 2, or if the first number is 2 and the second number is at least 15, the awk exit status will be "true". Otherwise, it will be false.

You can use this in a bash script like so:

if ldd --version | sed 's/.* //;q' | awk -F. '{ if ($1 > 2 || ($1 == 2 && $2 >= 15)) { exit 0 } else {exit 1} }' ; then
  echo "Version is 2.15 or later"
else
  echo "Version is too old."
fi
Related Question