2017-04-06 79 views
0

我正在嘗試在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因此超出了範圍。

+1

另外,建議使用['[''over'['](http://mywiki.wooledge.org/BashGuide/TestsAndConditionals#Conditional_Blocks_.28if.2C_test_and_.5B.5B.29)「。如果您只使用數字比較,請使用((('代替)。 –

回答

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 

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