Shell算术运算

算术运算:
运算符1:
+ - * / %(取余)
运算命令1:
expr 7 + 3
expr直接输出计算结果(区别于下边的运算命令)
注意中间的空格(如果没有会当成一个整体)且只能用于整数计算(区别于小数),另外使用来做乘法运算时要记得转义,因为有特殊的含义(通配符)。
[root@iLor shell_day01_am]# expr 7 + 3

10

[root@iLor shell_day01_am]# expr 7+3
7+3
[root@iLor shell_day01_am]# expr 7.19 + 3

expr: non-numeric argument

[root@iLor shell_day01_am]# expr 7 * 3
expr: syntax error
[root@iLor shell_day01_am]# expr 7 * 3

21

[root@iLor shell_day01_am]# expr 7 / 3
2
[root@iLor shell_day01_am]# expr 7 % 3

1

负数也是可以的
[root@iLor shell_day01_am]# expr 3 - 7

-4

运算符2:
   ++
   --
    +=
   -=
   *=

/=
%=
运算命令2:
let 很适合++和--这种运算符,不输出计算结果,且只能用于整数
如:
[root@iLor shell_day01_am]# i=1
[root@iLor shell_day01_am]# let i++
[root@iLor shell_day01_am]# echo (()) 适ech
a=0;echo a
a=0;echo a
echo默认换行,若想不换行用-n选项 echo –n

       let a+=2
   $[10+10] :类似于$(())和let +

运算命令3:
   bc可用于小数运算
       语法:echo “运算表达式” | bc
       (如果直接在命令行下输入bc,会进入交互模式,不灵活,此处的用法与非交互式修改用户密码)
          [root@iLor shell_day01_am]# echo "2+3" | bc

5
[root@iLor shell_day01_am]# echo "2.2+3" | bc
5.2
[root@iLor shell_day01_am]# echo "3/2" | bc
1
从上面看对运算结果取整了,如何保留小数,使用scale
[root@iLor shell_day01_am]# echo "scale=2;3/2" | bc
1.50





猜你喜欢

转载自www.cnblogs.com/whatislinux/p/7b7fdbc37847c561026e6999cfe98807.html
今日推荐