BASH – Comparison of decimal value with integer value

Let’s discuss how shell script behaves when we try to compare a numeric decimal value against integer.

Decimal value : Server load statistics, which need not to be integer value

[root@test tmp]# uptime
03:40:21 up 1 day, 20:17,  3 users,  load average: 2.82, 1.06, 0.39
[root@test tmp]#

Integer value : Processor count

[root@test ]# grep -c processor /proc/cpuinfo
1
[root@test ]#

Now let’s try to capture both output in shell variables and try to do a comparison. Storing values in variable and try to do a comparison.

[root@test ]# cat compare.sh
#!/bin/bash

LOADVALUE=`uptime | awk ‘{print $10}’ | cut -d ‘,’ -f 1`
CORE_VALUE=`grep -c processor /proc/cpuinfo`

if [ $LOADVALUE -ge $CORE_VALUE ]; then

echo “Server loaded”

else

echo “Server load OK”

fi
[root@test ]#

Now testing if script is working properly:

[root@test ]# sh compare.sh
compare.sh: line 6: [: 0.00: integer expression expected
[root@test ]#

Now its failing since we are trying to compare a string value against an integer in mathematical operator. Now try to use a scale factor.
Scale defines how some operations use digits after the decimal point.  The default value of scale is 0.

Modifying bash script with scale and comparing both decimal operators to provide a non-zero result.

[root@test ]# cat compare.sh
#!/bin/bash

LOADVALUE=`uptime | awk ‘{print $10}’ | cut -d ‘,’ -f 1`
CORE_VALUE=`grep -c processor /proc/cpuinfo`

if [[ $(echo “scale=2; $LOADVALUE > $CORE_VALUE” | bc) -ne 0 ]]; then

echo “Server loaded”

else

echo “Server load OK”

fi
[root@test ]#

[root@test ]# sh  compare.sh
Server loaded
[root@test ]#

Leave a comment