通过If语句确定数值是否超出范围

时间:2017-04-06 15:21:55

标签: linux bash unix if-statement

我正在尝试在IF中构建动态bash语句,以确定某个数字是否在预定义范围内或在其之外。

some.file

-11.6

Bash代码:

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

现在,我的回报是"价值在可接受的范围内"明确时,-11.6小于-7.0,因此超出范围。

1 个答案:

答案 0 :(得分:1)

试试这个 -

$ 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

$ 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

处理......

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