shell expr 案例
时间: 2024-04-21 19:27:28 浏览: 15
当使用`expr`命令时,可以通过使用操作符和表达式来执行不同的操作。下面是一些常见的`expr`命令案例:
1. 计算两个整数的和:
```shell
sum=$(expr 10 + 5)
echo "Sum: $sum" # 输出:Sum: 15
```
2. 计算两个整数的差:
```shell
difference=$(expr 20 - 8)
echo "Difference: $difference" # 输出:Difference: 12
```
3. 计算两个整数的乘积:
```shell
product=$(expr 6 \* 4)
echo "Product: $product" # 输出:Product: 24
```
4. 计算两个整数的商:
```shell
quotient=$(expr 20 / 4)
echo "Quotient: $quotient" # 输出:Quotient: 5
```
5. 比较两个整数是否相等:
```shell
a=10
b=10
if [ $(expr $a = $b) -eq 1 ]; then
echo "Numbers are equal."
else
echo "Numbers are not equal."
fi
```
6. 获取字符串的长度:
```shell
string="Hello World!"
length=$(expr length "$string")
echo "Length: $length" # 输出:Length: 12
```
这些案例演示了`expr`命令在进行数学运算和字符串处理时的常见用法。你可以根据自己的需求进行修改和扩展。
希望以上案例对你有所帮助。如果还有其他问题,请随时提问!