自带的运算命令:expr
[[email protected] ~]# expr 1 + 5 加 6 [[email protected] ~]# expr 20 - 5 减 15 [[email protected] ~]# expr 20 \* 5 乘 100 [[email protected] ~]# expr 20 \/ 5 除 4 [[email protected] ~]# expr 22 \% 5 余 2
[[email protected] ~]# v1=10 [[email protected] ~]# v2=20 [[email protected] ~]# v3=`expr $v2 / $v1` [[email protected] ~]# echo $v3 2 [[email protected] ~]# v1=$[1 + 5] [[email protected] ~]# echo $v1 6
浮点计算:bc
安装bc
[[email protected] ~]# yum -y install bc.x86_64
[[email protected] ~]# bc bc 1.06.95 Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc. This is free software with ABSOLUTELY NO WARRANTY. For details type `warranty‘. 1.2 * 2.1 #计算1.2乘以2.1的结果 2.5 1.2 * 2.10 2.52 3 / 2 1 scale=4 //设置计算结果保留的小数位数,scale默认的值为0 3 / 2 1.5000 5 / 3 1.6666
[[email protected] ~]# bc -q #-q屏蔽打开bc计算器时的软件说明 1.3 / 2 0 scale=4 1.3 / 2 .6500 2 / 1.5 1.3333
bc中引用赋值变量:
[[email protected] ~]# bc -q scale=4 a1=2016 a1 * 20 40320 b1 = a1 / 365 print b1 5.5232 quit #退出
在脚本中使用bc:
基本格式:variable(变量)=`echo "options;expression" |bc `
[[email protected] ~]# vim test.sh #!/bin/bash v1=`echo "scale=4; 3 / 2" | bc` echo v1=$v1 [[email protected] ~]# sh test.sh v1=1.5000
[[email protected] ~]# vim test.sh #!/bin/bash v1=2016 v2=365 v3=`echo "scale=4; $v1 / $v2" | bc` echo v3=$v3 [[email protected] ~]# sh test.sh v3=5.5232
[[email protected] ~]# cat test.sh #!/bin/bash v1=2016 v2=365 v3=`echo "scale=4; $v1 / $v2" | bc` v4=`echo "scale=4; $v3 * $v2" | bc` echo v4=$v4 [[email protected] ~]# sh test.sh v4=2015.9680
bc内联输入重定向:
[[email protected] ~]# cat test.sh #!/bin/bash v1=2016 v2=365 v3=10 v4=5000 v5=`bc << EOF scale = 4 a1 = ( $v4 / $v2 ) a2 = ( $v3 * $v2 ) a1 + a2 EOF ` echo v5=$v5 [[email protected] ~]# sh test.sh v5=3663.6986
时间: 2024-12-22 00:35:30