Shell编程-算术运算符

时间:2020-02-23 14:45:06  来源:igfitidea点击:

在本教程中,我们将学习Shell编程中的算术运算符。

在本教程中,我们将介绍以下数学运算。

  • 加法+
  • 减法
  • 乘法*
  • 除非/
  • 模数%得到余数

expr命令

在Shell脚本中,所有变量都保留字符串值,即使它们是数字也是如此。
因此,为了执行算术运算,我们使用了expr命令。

expr命令只能使用整数值。
对于浮点数,我们使用bc命令。

为了计算结果,我们将表达式括在反引号 "`" 中。

加法

我们使用" +"符号执行加法。

在下面的示例中,我们从用户获取两个整数值,并显示加法后的结果。

#!/bin/sh

# take two integers from the user
echo "Enter two integers: "
read a b

# perform addition
result=`expr $a + $b`

# show result
echo "Result: $result"

在上面的脚本中,expr $a + $b表示我们要添加存储在变量a和b中的值,并使用expr命令评估表达式。
然后,我们将加法运算的结果保存在变量result中。

$sh add.sh
Enter two integers: 
10 20
Result: 30

在下面的示例中,我们将变量括在双引号中,并使用bc处理浮点数。

#!/bin/sh
  
# take two numbers from the user
echo "Enter two numbers: "
read a b

# perform addition
result=`expr "$a + $b" | bc`

# show result
echo "Result: $result"
$sh add2.sh 
Enter two numbers: 
1.2 3.4 
Result: 4.6

减法

为了执行减法,我们使用-符号。

在下面的示例中,我们将从用户那里获得两个数字并打印减法结果。

#!/bin/sh

# take two numbers from user
echo "Enter two numbers: "
read a b

# compute subtraction result
result=`expr "$a - $b" | bc`

# print output
echo "Result: $result"
$sh subtract.sh 
Enter two numbers: 
10 9
Result: 1

$sh subtract.sh 
Enter two numbers: 
9 10
Result: -1

$sh subtract.sh 
Enter two numbers: 
10.5 9.1
Result: 1.4

乘法

为了执行乘法,我们使用" *"符号。

在下面的示例中,我们将两个数字相乘。

#!/bin/sh

# take two numbers from user
echo "Enter two numbers: "
read a b

# compute multiplication result
result=`expr "$a * $b" | bc`

# print output
echo "Result: $result"
$sh multiplication.sh 
Enter two numbers: 
2 3
Result: 6

$sh multiplication.sh 
Enter two numbers: 
-2 3
Result: -6

$sh multiplication.sh 
Enter two numbers: 
1.5 4
Result: 6.0

除法

为了执行除法,我们使用/符号。

在下面的示例中,我们将两个数字相除。

#!/bin/sh

# take two numbers from user
echo "Enter two numbers: "
read a b

# compute division result
result=`expr "$a/$b" | bc -l`

# print output
echo "Result: $result"
$sh division.sh 
Enter two numbers: 
4 2
Result: 2

$sh division.sh 
Enter two numbers: 
5 2
Result: 2.50000000000000000000

-l选项加载默认比例设置为20的标准数学库。

取模

为了执行模数运算,我们使用"%"符号。

在下面的示例中,我们将通过除以两个数得到余数。

#!/bin/sh

# take two numbers from user
echo "Enter two numbers: "
read a b

# compute modulus result
result=`expr "$a % $b" | bc`

# print output
echo "Result: $result"
$sh modulus.sh 
Enter two numbers: 
5 2
Result: 1

$sh modulus.sh 
Enter two numbers: 
5.1 2
Result: 1.1