5-2-shell:数值处理--加减乘除
一、整数
加减乘除
echo `expr 2 + 1` echo `expr 2 - 1` echo `expr 2 \* 1` echo `expr 2 / 1`
比较
-eq 等于,如:if [ "$a" -eq "$b" ] -ne 不等于,如:if [ "$a" -ne "$b" ] -gt 大于,如:if [ "$a" -gt "$b" ] -ge 大于等于,如:if [ "$a" -ge "$b" ] -lt 小于,如:if [ "$a" -lt "$b" ] -le 小于等于,如:if [ "$a" -le "$b" ] < 小于(需要双括号),如:(("$a" < "$b")) <= 小于等于(需要双括号),如:(("$a" <= "$b")) > 大于(需要双括号),如:(("$a" > "$b")) >= 大于等于(需要双括号),如:(("$a" >= "$b"))
二、浮点数-bc
使用awk或者bc计算
加减乘除
精度丢失 echo "0.2+2.5"|bc echo "0.2-2.5"|bc echo "0.2*2.5"|bc --结果.5 echo "2.5/0.2"|bc --结果12
比较
if [ $(echo '5.2 > 2'|bc) = 1 ] then echo "test" fi
差值比较
a=5.2 b=2 if [ `echo "$a - $b > 1"|bc` = 1 ] then echo "test greater" fi if [ `echo "$a - $b == 3.2"|bc` = 1 ] then echo "test equal" fi
二、浮点数-awk
使用awk或者bc计算
加减乘除
完整计算 a=5.2 b=2 echo "$a $b" | awk '{printf("%0.3f\n",$1+$2)}' echo "$a $b" | awk '{printf("%0.3f\n",$1-$2)}' echo "$a $b" | awk '{printf("%0.3f\n",$1×$2)}' echo "$a $b" | awk '{printf("%0.3f\n",$1/$2)}'
比较
a=5.2 b=2 if [ $(echo "$a $b" | awk '{printf("%d\n",$1<$2)}') = 1 ] then echo "test" fi
差值比较
a=5.2 b=2 if [ `echo "$a $b" | awk '{printf("%d\n",$1<$2)}'` = 1 ] then echo "test greater" fi if [ `echo "$a - $b == 3.2"|bc` = 1 ] then echo "test equal" fi