arnpry
arnpry

Reputation: 1141

Determine If Numeric Value Is out of Range via If Statement

I am trying to construct a dynamic IF statement in bash to determine if a number is within a pre-defined range or outside of it.

some.file

-11.6

Bash Code:

check=`cat some.file`

if [ ${check} -le "-7.0" ] && [ ${check} -ge "7.0" ];
then
echo "CAUTION: Value outside acceptable range"
else
echo "Value within acceptable range"
fi

Right now, I am getting returns of "Value within acceptable range" when clearly, -11.6 is less than -7.0 and therefore out of the range.

Upvotes: 0

Views: 160

Answers (1)

VIPIN KUMAR
VIPIN KUMAR

Reputation: 3147

Try this -

$ cat f
2
$ awk '{if($1 >= -7.0 && $1 <= 7.0) {print "Value within acceptable range"} else {print "CAUTION: Value outside acceptable range"}}' f
Value within acceptable range

$ cat f
-11.6
$ awk '{if($1 >= -7.0 && $1 <= 7.0) {print "Value within acceptable range"} else {print "CAUTION: Value outside acceptable range"}}' f
CAUTION: Value outside acceptable range

OR

$ cat kk.sh
while IFS= read -r line
do
if [ $line -ge -7.0 ] && [ $line -le 7.0 ]; then
echo "Value within acceptable range"
else
echo "CAUTION: Value outside acceptable range"
fi
done < f

Processing ...

$ cat f
2
$ ./kk.sh
Value within acceptable range

$ cat f
-11.2
$ ./kk.sh
CAUTION: Value outside acceptable range

Upvotes: 1

Related Questions