shell脚本(变量的运算)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了shell脚本(变量的运算)相关的知识,希望对你有一定的参考价值。

变量的运算

方法一:expr

(直接命令行操作即可)
##加减乘除

[[email protected] ~]# num1=10
[[email protected] ~]# num2=16
[[email protected] ~]# expr $num1 + num2
25
[[email protected] ~]# expr $num2 - num1
6
[[email protected] ~]# expr $num1 \* num2
160
[[email protected] ~]# expr $num2 \ num1 #默认不显示小数,取整
1

方法二:$(())

$符号加(())

[[email protected] ~]# num1=10
[[email protected] ~]# num2=16
[[email protected] ~]# echo $(($num1+$num2)) #加
26
[[email protected] ~]# echo $(($num1-$num2)) #减
-6
[[email protected] ~]# echo $(($num1*$num2)) #乘
160
[[email protected] ~]# echo $(($num2/$num1)) #除,默认取整数,不显示小数
1

方法三:$[]

$符号加[]

[[email protected] ~]# num1=10
[[email protected] ~]# num2=16
[[email protected] ~]# echo $[num1 + num2] #加
26
[[email protected] ~]# echo $[num1 - num2] #减
-6
[[email protected] ~]# echo $[num1 * num2] #乘
160
[[email protected] ~]# echo $[num2 / num1] #除,同上
1

方法四:let

let不直接输出

[[email protected] ~]# num1=10
[[email protected] ~]# num2=16
[[email protected] ~]# let sum=$num1+$num2;echo $sum #加
26
[[email protected] ~]# let sum=$num1-$num2;echo $sum #减
-6
[[email protected] ~]# let sum=$num1*$num2;echo $sum #乘
160
[[email protected] ~]# let sum=$num2/$num1;echo $sum #除
1

扩展:小数运算bc

scale=n;定义小数精度,此外可以直接运行bc命令进行输入计算

[[email protected] ~]# num1=1.8
[[email protected] ~]# num2=2.2
[[email protected] ~]# echo "scale=3;$num1+$num2" | bc
4.0
[[email protected] ~]# echo "scale=2;$num2-$num1" | bc
.4
[[email protected] ~]# echo "scale=2;$num2/$num1" | bc
1.22
[[email protected] ~]# echo "scale=2;$num2*$num1" | bc
3.96

扩展:小数运算awk

awk -v 带入外部变量,‘ print num1 + num2 ‘即可

[[email protected] project]# num1=2.1
[[email protected]localhost project]# num2=1.5
[[email protected] project]# echo | awk -v num1=$num1 -v num2=$num2 "print num1 + num2 "
3.6
[[email protected] project]# echo | awk -v num1=$num1 -v num2=$num2 "print num1 - num2 "
0.6
[[email protected] project]# echo | awk -v num1=$num1 -v num2=$num2 "print num1 * num2 "
3.15
[[email protected] project]# echo | awk -v num1=$num1 -v num2=$num2 "print num1 / num2 "
1.4

以上是关于shell脚本(变量的运算)的主要内容,如果未能解决你的问题,请参考以下文章

shell脚本变量数值计算

shell脚本:变量,文件判断,逻辑运算等纪要

shell脚本(变量的运算)

Linux系统编程-Shell脚本基本使用(变量运算符语句等)

Shell入门变量的使用

Shell脚本保姆级教程