SHELL脚本小数比较

由于脚本需要,可能会涉及到小数判断,如:

[[email protected] logs]# ls -lh . | awk '{print $NF "\t" $5}' | sort -h -k 2 -r | grep G$ | awk '{print $NF}' | sed 's/G//'      
3.5

但SHELL默认的判断中只支持整数判断,如:

[[email protected] logs]# if [[ 11 -ge 10 ]];then echo "true";else echo "flase";fi 
true
[[email protected] logs]# if (( 11 >= 10 ));then echo "true";else echo "flase";fi 
true

当对象是小数时就会报错:

[[email protected] logs]# if [[ 3.5 -ge 10 ]];then echo "true";else echo "flase";fi  
-bash: [[: 3.5: syntax error: invalid arithmetic operator (error token is ".5")
flase
[[email protected] logs]# if (( 3.5 >= 10 ));then echo "true";else echo "flase";fi    
-bash: ((: 3.5 >= 10 : syntax error: invalid arithmetic operator (error token is ".5 >= 10 ")
flase

这时可以使用bc命令,bc是一个计算器,Bash内置了对整数四则运算的支持,但是并不支持浮点运算,而bc命令可以很方便的进行浮点运算,当然也可以进行整数运算。

[[email protected] logs]# if [[ $(echo "3.5 >= 10" | bc) -eq 1 ]];then echo "true";else echo "flase";fi  
flase
[[email protected] logs]# if [[ $(echo "10.1 >= 10" | bc) -eq 1 ]];then echo "true";else echo "flase";fi   
true

留下评论

error: Content is protected !!