SHELL脚本编程的运算符

                             作者:尹正杰

版权声明:原创作品,谢绝转载!否则将追究法律责任。

 

 

一.算数运算
1>.bash中的算数运算
[root@node101.yinzhengjie.org.cn ~]# help let
let: let arg [arg ...]
    Evaluate arithmetic expressions.
    
    Evaluate each ARG as an arithmetic expression.  Evaluation is done in
    fixed-width integers with no check for overflow, though division by 0
    is trapped and flagged as an error.  The following list of operators is
    grouped into levels of equal-precedence operators.  The levels are listed
    in order of decreasing precedence.
    
        id++, id--    variable post-increment, post-decrement
        ++id, --id    variable pre-increment, pre-decrement
        -, +        unary minus, plus
        !, ~        logical and bitwise negation
        **        exponentiation
        *, /, %        multiplication, division, remainder
        +, -        addition, subtraction
        <<, >>        left and right bitwise shifts
        <=, >=, <, >    comparison
        ==, !=        equality, inequality
        &        bitwise AND
        ^        bitwise XOR
        |        bitwise OR
        &&        logical AND
        ||        logical OR
        expr ? expr : expr
                conditional operator
        =, *=, /=, %=,
        +=, -=, <<=, >>=,
        &=, ^=, |=    assignment
    
    Shell variables are allowed as operands.  The name of the variable
    is replaced by its value (coerced to a fixed-width integer) within
    an expression.  The variable need not have its integer attribute
    turned on to be used in an expression.
    
    Operators are evaluated in order of precedence.  Sub-expressions in
    parentheses are evaluated first and may override the precedence
    rules above.
    
    Exit Status:
    If the last ARG evaluates to 0, let returns 1; let returns 0 otherwise.
[root@node101.yinzhengjie.org.cn ~]# 
[root@node101.yinzhengjie.org.cn ~]# help let
+, -, *, /, %取模(取余), **(乘方),乘法符号有些场景中需要转义。

实现算术运算:
  (1) let var=算术表达式
  (2) var=$[算术表达式]
  (3) var=$((算术表达式))
  (4) var=$(expr arg1 arg2 arg3 ...)
  (5) declare –i var = 数值
  (6) echo ‘算术表达式’ | bc

增强型赋值:
  +=, -=, *=, /=, %=

let varOPERvalue
  例如:let count+=3
  自加3后自赋值

自增,自减:
  let var+=1
  let var++
  let var-=1
  let var--

相关文章: