Bash 脚本 – 算术运算符
在本文中,我们将看到 bash 脚本中的算术运算符。算术运算符用于执行算术运算。
Bash 脚本支持 11 个算术运算运算符。下面给出了所有运算符及其用途: 16/3 result = 5 16/ 3 result = 1 x= 13 x+=3 result = 16 x= 13 x -= 3 result = 10 x= 10 x*=3 result = 30 x = 31 x/=3 result = 10 x= 31 x%=3 result = 1 3**2 result = 9Operator Name Use Example + Addition It adds two operands result= a+b – Subtraction It subtract second operand from first one result= a-b * Multiplication Multiply two operands result= a*b / Division Return the quotient after diving first operand from second operands % Modulo Return remainder after dividing first operand from second operand += Increment by constant Increment value of first operand with given constant value -= Decrement by constant Decrement value of first operand with given constant value *= Multiply by constant Multiply the given operand with the constant value /= Divide by constant Divide the operand with given constant value and return the quotient %= Remainder by dividing with constant Divide the operand with given constant value and return the remainder ** Exponentiation The result is second operand raised to the power of first operand.
让我们看看算术运算运算符的使用示例:
添加
代码:
Sum=$((10+3))
echo "Sum = $Sum"
输出:
减法
代码:
Difference=$((10-3))
echo "Difference = $Difference"
输出:
乘法
代码:
Product=$((10*3))
echo "Product = $Product"
输出:
分配
代码:
Division=$((10/3))
echo "Division = $Division"
输出:
模数
代码:
Modulo=$((10%3))
echo "Modulo = $Modulo"
输出:
求幂
代码:
Exponent=$((10**2))
echo "Exponent = $Exponent"
输出:
显示在单个代码中使用所有运算符的示例
代码:
x=10
y=20
echo "x=10, y=5"
echo "Addition of x and y"
echo $(( $x + $y ))
echo "Subtraction of x and y"
echo $(( $x - $y ))
echo "Multiplication of x and 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 10, then x= "
(( x += 10 ))
echo $x
echo "Decrementing x by 15, then x= "
(( x -= 15 ))
echo $x
echo "Multiply of x by 2, then x="
(( x *= 2 ))
echo $x
echo "Dividing x by 5, x= "
(( x /= 5 ))
echo $x
echo "Remainder of Dividing x by 5, x="
(( x %= 5 ))
echo $x
输出:
在 Bash 中计算算术运算的不同方法
有一些不同的方法来执行算术运算。
1.双括号
这可以用于算术扩展。让我们看一个例子来看看双引号的使用。
代码:
#!/bin/bash
first=10
second=3
echo $(( first + second )) # addition
echo $(( $first + $second )) # this is also valid
echo $(( first - second )) # subtraction
echo $(( $first - $second )) # this is also valid
输出:
13
13
7
7
2.使用let命令
let 命令用于执行算术运算。
例子
代码:
#!/bin/bash
x=10
y=3
let "z = $(( x * y ))" # multiplication
echo $z
let z=$((x*y))
echo $z
let "z = $(( x / y ))" # division
echo $z
let z=$((x/y))
echo $z
输出:
30
30
3
3
3. 带反引号的 expr 命令
算术扩展可以使用反引号和 expr 来完成。
代码:
a=10
b=3
# there must be spaces before/after the operator
sum=`expr $a + $b`
echo $sum
sub=`expr $a - $b`
echo $sub
mul=`expr $a \* $b`
echo $mul
div=`expr $a / $b`
echo $div
输出:
13
7
30
3