【shell】数字运算的几种方式

本文详细介绍了Shell中进行整数运算的五种方法,包括expr命令、$(())语法、$[]语法、let命令及bc命令,并展示了每种方法的具体用法实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

shell中的整数运算包括,加减乘除取余,+,-,*(*是元字符,表示任意一个字符,所以需要转义),/,%。

方法一:expr

[root@#test test]# expr 1 + 2
3
[root@#test test]# a=1
[root@#test test]# b=3
[root@#test test]# expr $a + $b
4

注意:运算符(+,-,*,/)前后一定要有空格!!!

方法二:$(())

[root@#test test]# num1=10
[root@#test test]# num2=20
[root@#test test]# 
[root@#test test]# echo $(($num1+$num2))
30
[root@#test test]# echo $((num1+num2))
30
[root@#test test]# echo $((2*5-3))
7
[root@#test test]# result=$((2+3))
[root@#test test]# echo $result
5

方法三:$[]

同$(())类似

[root@#test test]# num1=10
[root@#test test]# num2=20
[root@#test test]# echo $[num1+num2]
30
[root@#test test]# echo $[2*5-9]
1

方法四:let

[root@#test test]# let c=1+2
[root@#test test]# echo $c
3
[root@#test test]# 
[root@#test test]# a=1
[root@#test test]# b=3
[root@#test test]# let c=$a+$b
[root@#test test]# echo $c
4

方法五:bc命令支持小数运算

需要先安装:yum install bc

[root@#test test]# echo "23.89+45.9877"|bc
69.8777
[root@#test test]# 
[root@#test test]# echo "1+2"|bc
3
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值