# Bash算术运算符

Bash Shell支持11种算术运算符。

`+`加法，数字(操作数)的加法`\$(( 10 + 3 ))`，结果为：`13`
`-`减法，从第一个到第二个操作数的减法`\$(( 10 - 3 ))`，结果为：`7`
`*`乘法，操作数的乘法。`\$(( 10 * 3 ))`，结果为：`30`
`/`除法，第一个操作数除以第二个操作数并返回商。`\$(( 10 / 3 ))`，结果为：`3`
`**`求幂，第一操作数的第二操作数的幂值。`\$(( 10 ** 3 ))`，结果为：`1000`
`%`模，测量第一个操作数除以第二个操作数时的余数。`\$(( 10 % 3 ))`，结果为：`1`
`+=`通过常量递增变量，用于按提供的常量递增第一个操作数的值。`x=10;let "x += 3";echo \$x;`结果为：`13`
`-=`通过常量递减变量，用于按提供的常量递减第一个操作数的值。`x=10;let "x -= 3";echo \$x;`结果为：`7`
`*=`将变量乘以常数，用于将第一个操作数的值乘以提供的常数。`x=10;let "x *= 3";echo \$x;`结果为：`30`
`/=`将变量除以常数，用于计算(变量/常数)的值并将结果存储回变量。`x=10;let "x /= 3";echo \$x;`结果为：`3`
`%=`变量除以常数的余数，用于计算(变量％常数)的值并将结果存储回变量。`x=10;let "x %= 3";echo \$x;`结果为：`1`

## 1. Bash执行算术运算

#### 1.1. 双括号

``````((expression))
``````

``````Sum=\$((10+3))
echo "Sum = \$Sum"
``````

``````((Sum=10+3))
echo "Sum = \$Sum"
``````

``````Num1=10
Num2=3
((Sum=Num1+Num2))
echo "Sum = \$Sum"
``````

``````Num1=10
Num2=3
Sum=\$((Num1+Num2))
echo "Sum = \$Sum"
``````

``````Sum = 13
``````

Bash脚本文件：arithmetic-operator.sh

``````#!/bin/bash

x=6
y=10
echo "x=6, y=10"
echo "Addition of x & y"
echo \$(( \$x + \$y ))
echo "Subtraction of x & y"
echo \$(( \$x - \$y ))
echo "Multiplication of x & y"
echo \$(( \$x * \$y ))
echo "Division of x by y"
echo \$(( \$x / \$y ))
echo "Exponentiation of x,y"
echo \$(( \$x ** \$y ))
echo "Modular Division of x,y"
echo \$(( \$x % \$y ))
echo "Incrementing x by 5, then x= "
(( x += 5 ))
echo \$x
echo "Decrementing x by 5, then x= "
(( x -= 5 ))
echo \$x
echo "Multiply of x by 5, then x="
(( x *= 5 ))
echo \$x
echo "Dividing x by 5, x= "
(( x /= 5 ))
echo \$x
echo "Remainder of Dividing x by 5, x="
(( x %= 5 ))
echo \$x
``````

#### 1.2. Let构建

`let`是Bash的内置命令，它能够执行算术运算。它遵循以下基本语法格式：

``````let <arithmetic expression>
``````

``````#!/bin/bash

x=10
y=6
z=0
let "z = \$(( x + y ))"
echo "z= \$z"

echo "Substraction"
let "z = \$((x - y ))"
echo "z= \$z"

echo "Multiplication"
let "z = \$(( x * y ))"
echo "z = \$z"

echo "Division"
let "z = \$(( x / y ))"
echo "z = \$z"

echo "Exponentiation"
let "z = \$(( x ** y ))"
echo "z = \$z"

echo "Modular Division"
let "z = \$(( x % y ))"
echo "z = \$z"

let "x += 5"
echo "Incrementing x by 5, then x= "
echo \$x

let "x -= 5"
echo "Decrementing x by 5, then x= "
echo \$x

let "x *=5"
echo "Multiply of x by 5, then x="
echo \$x

let "x /= 5"
echo "Dividing x by 5, x= "
echo \$x

let "x %= 5"
echo "Remainder of Dividing x by 5, x="
echo \$x
``````

#### 1.3. 反引号

```````expr`
``````

```````expr`
``````

```````expr`
```。

**语法**

```bash
`expr item1 operator item2`
#或者
expr item1 operator item2
``````

Bash脚本程序文件：backticks.sh，完整代码如下：

``````#!/bin/bash
#Basic arithmetic using expr

echo "a=10, b=20"
echo "c is the value of addition c=a+b"
a=10
b=20
echo "c= `expr \$a + \$b`"
``````

原文作者：Bash Shell教程
原文地址: https://www.yiibai.com/bash/bash-arithmetic-operators.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。
点赞