Suresh Rajasekaran
Suresh Rajasekaran

Reputation: 19

How to compare decimal numbers in shell script?

#!/bin/bash
for input in $(cat status_cpu.txt)
do
      cpu=`ssh -i  root@$input 'top -b -n1' | grep "load" | awk '{print $12}'`

      max=2.02

if [ $(echo "$cpu < $max" | bc -l ) ]; then
    echo "yes"
else
    echo "no" 
fi
done  

cat status_cpu.txt
10.0.0.1
10.0.0.2

I want to compare decimal points in shell script.

Upvotes: 1

Views: 6241

Answers (3)

Jotne
Jotne

Reputation: 41460

You do not need to use awk and grep in same line, awk does it all.
Do not use old and outdated back-tics, use parentheses.

So this would change from:

cpu=`ssh -i  root@$input 'top -b -n1' | grep "load" | awk '{print $12}'`

To:

cpu=$(ssh -i  root@$input 'top -b -n1' | awk '/load/ {print $12}')

And this:

if [ $(echo "$cpu < $max" | bc -l ) -eq 1 ]; then
    echo "yes"
else
    echo "no" 
fi

Could be written

[ $(echo "$cpu < $max" | bc -l ) -eq 1 ] && echo "yes" || echo "no"

or

[[ $(echo "$cpu < $max" | bc -l ) -eq 1 ]] && echo "yes" || echo "no"

Upvotes: 2

zenaan
zenaan

Reputation: 871

Here's how to put this into a Posix shell function which can thereafter be easily used in shell tests (presumably bc reserves return codes for error codes):

ifbc () { test $(echo "$@" | bc -l ) -ne 0; }

And an example usage of this function:

ifbc "$max > $s" && echo "true, it's greater" || echo "no, it's less or ="

Upvotes: 0

anubhava
anubhava

Reputation: 785541

You can use comparison using bc -l like this:

max='2.02'
s='2.01'

bc -l <<< "$max > $s"
1

s='2.05'
bc -l <<< "$max > $s"
0

So bc -l expression will print 1 for success and 0 for failure.

Upvotes: 1

Related Questions