确定如果数值通过If语句超出范围
问题描述:
我正在尝试在bash
中构造一个动态IF
语句,以确定某个数字是否在预定义范围内或其外部。确定如果数值通过If语句超出范围
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
因此超出了范围。
答
试试这个 -
$ 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
处理...
$ cat f
2
$ ./kk.sh
Value within acceptable range
$ cat f
-11.2
$ ./kk.sh
CAUTION: Value outside acceptable range
另外,建议使用['[''over'['](http://mywiki.wooledge.org/BashGuide/TestsAndConditionals#Conditional_Blocks_.28if.2C_test_and_.5B.5B.29)“。如果您只使用数字比较,请使用((('代替)。 –