shell变量数值计算

版权声明:silly8543 https://blog.csdn.net/cen50958/article/details/89848925
  • (()) 执行简单的整数运算(高效常用)
运算符 描述
++ -- 增加 减少
+ - ! ~ 一元运算符 正号 负号 非 取反
* / % 乘法 除法 取余
+ - 加法 减法
< <= > >= 小于 小于等于 大于 大于等于
== != 相等 不相等
<< >> 向左位移 向右位移
& 位的AND
^ 位的异或
| 位的或
&& 逻辑AND
|| 逻辑OR
? : 条件表达式
= += -= *= /= %= &= ^=
<<= >>= |=
赋值运算符

[root@study ~]# ((a= 1+2+4+5*1+7/9 ))
[root@study ~]# echo $a
12


[root@study ~]# b=$((1+2+4+5*1+7/9 ))
[root@study ~]# echo $b
12


[root@study ~]# echo $((1+2+4+5*1+7/9 ))
12

  • let(bash内部命令) 赋值表达式(效率低)

    [root@study ~]# a=3
    [root@study ~]# let a=a+3
    [root@study ~]# echo $a
    6

  • expr 一般用于整数值,但也可用于字符串,用来求表达式变量的值,同时expr也是一个手工命令行计算器

    [root@study ~]# expr 1 + 2 + 4 + 5 * 1 + 7 / 9    —>注意数字与运算符都有空格
    12


    [root@study ~]# expr 1+2+4+5*1+7/9
    1+2+4+5*1+7/9


    [root@study ~]# expr $[1+2+4+5*1+7/9]
    12

  • bc 是unix下的计算器,可以支持小数运算

    [root@study ~]# 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
    3
    3*9
    27
    9-1
    8


    [root@study ~]# echo 2*9|bc
    18

  • $[]

    [root@study ~]# echo $[2*3]
    6

猜你喜欢

转载自blog.csdn.net/cen50958/article/details/89848925