27. 算数运算符


运算符 描述
+
-
*
/
% 求模(取余,整数除法的余数,例如: 7%2 = 1
** 求幂(例如,10**4 = 10*10*10*10

您可以使用快捷算术运算符+=,而不是total=$total+5,如下所示。

total+=5

  • += 加等于(将变量增加一个常数)
  • -= 减等于(将变量减少一个常数)
  • *= 倍等于(变量乘以常量)
  • /= 除等于(变量除以常量)
  • %= 模等于(取余,变量除以常数的余数)

自动递增、递减:

let total++
let total--

下面是一个示例 shell 脚本,演示了各种算术运算符:

$ cat arithmetic.sh
#!/bin/bash
echo "Basic Arithmetic Operators"
total=10
echo "total = $total"
let total=$total+1
echo "total+1 = $total"
(( total=$total-1 ))
echo "total-1 = $total"
total=`expr 10 \* 2`
echo "total*2 = $total"
let total=$total/2
echo "total/2 = $total"
((total=$total**4))
echo "total%5 = $total"
total=`expr $total % 3`
echo "total%3 = $total"
echo "Shortcut Arithmetic Operators"
total=10
echo "total = $total"
let total+=5
echo "total+=5 is $total"
((total-=5))
echo "total-=5 is $total"
let total*=5
echo "total*=5 is $total"
let total/=5
echo "total/=5 is $total"
let total%=3
echo "total%=3 is $total"
echo "Auto increment and decrement"
let total++
echo "total++ is $total"
((total--))
echo "total-- is $total"

以下是上述算术 shell 脚本的输出。

$ ./arithmetic.sh
Basic Arithmetic Operators
total = 10
total+1 = 11
total-1 = 10
total*2 = 20
total/2 = 10
total%5 = 10000
total%3 = 1
Shortcut Arithmetic Operators
total = 10
total+=5 is 15
total-=5 is 10
total*=5 is 50
total/=5 is 10
total%=3 is 1
Auto increment and decrement
total++ is 2
total-- is 1

Bash 不理解浮点运算。 它将包含小数点的数字视为字符串。 即使您使用 let(( ))expr,此限制也适用。

$ total=1.5
$ let total=$total+1
-bash: let: total=1.5+1: syntax error: invalid arithmetic operator (error token is ".5+1")

另请注意,如果将expr用于算术表达式,则需要为大多数算术运算符指定转义字符 (\)。 例如,*需要一个转义字符,如下所示。

$ expr 2 * 3
expr: syntax error
$ expr 2 \* 3
6

Bash 根据运算符的 优先级 以特定顺序计算表达式。 下表首先列出了优先级最高的运算符。 为了完全安全,请使用括号来控制计算顺序!

运算符 描述
var++var-- 后置自动递增和自动递减
++var--var 前置自动递增和自动递减
-+ 一元减号和加号
!~ 逻辑非和按位求反
** 求幂
*/% 乘法、除法和取余(模)运算符
+- 加法和减法
<<>> 按位左移和右移
<=>=<> 比较运算符
==!= 相等和不相等
&^| 运算符的优先级与书写顺序相同。 与、异或、或
&& 逻辑与
|| 逻辑或
expr ? expr : expr 三元运算符
=, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |= 作业