bin bash decimal compare

I need decimal comparing with if. Check if apache version is less than 2.2.17.

I tried this and not working.

#!/bin/bash

apachever=`/usr/local/apache/bin/httpd  -v | head -1 | awk '{print $3}' |cut -d/ -f 2`

if [[ $(echo "$apachever < 2.2.17" |bc) -eq 1 ]]; then
        echo "Apache version less than 2.2.17"
else
        echo "Apache version greater or equal to 2.2.17"
fi

try with ksh

@anil510: From math perspective, is "2.2.17" a number? How can you expect bc to evaluate two such strings?

One alternative is to first split the major version, minor version and build number, hold them in an array and then compare them.

awk will compare the values

$ echo "2.2.25" | nawk '{if($0>"2.2.28"){print "Hi"}else{print "Hello"}}'
Hello
$ echo "2.2.25" | nawk '{if($0>"2.2.20"){print "Hi"}else{print "Hello"}}'
Hi
1 Like

That won't work. That string comparison will consider 2.2.3 greater than 2.2.20. Each component of the version string needs to be considered separately and must be treated numerically.

Regards,
Alister

Hi.

Note that some non-numeric characters might be found in some v.r.l strings:

       The version is always described with a triple <version,revision,level>
       and is represented by a string which always matches the regular
       expression ""[0-9]+\.[0-9]+[sabp.][0-9]+"".

-- excerpt from man shtool-version

although I have not seen the sabp in, for example, the apache2 version on my system. An example from the man page is 1.2b3

I have seen instances where an underline is used: java version "1.6.0_22"

Best wishes ... cheers, drl

1 Like
apachever=`/usr/local/apache/bin/httpd  -v | head -1 | awk '{print $3}' |cut -d/ -f 2`
apachever=$(httpd -v | awk -F'[ /]' '{print $4}')

IFS=. read -r v r l <<< "$apachever"
if (( v >= 2 && r >= 2 && l >= 17 )); then
  :
fi

Hi,

#!/bin/bash

apachever=$(/usr/local/apache/bin/httpd  -v | head -1 | awk '{print $3}' |cut -d/ -f 2)
minval=$( echo -e "$apachever\n2.2.17" | sort -n -t . -k 1,1 -k 2,2 -k 3,3 | head -1 )

if [ "$minval" = "2.2.17" ]; then
	echo "Apache version $apachever greater or equal to 2.2.17"
else
	echo "Apache version $apachever less than 2.2.17"
fi
1 Like