linux shell 约等于 =,shell算术运算

在shell中算术运算方法有几种 1. expr 2. let 3.$[] 4.bc计算器

这里主要计算$[] 和 bc 计算器,因为这是我觉得好用的两种方式

方式一:$[]

注意:这种方式不支持浮点数运算

普通返回

vim test_yunsuan.sh

1 # /bin/bash

2 fund(){

3 a=1

4 b=2

5 echo $[1 + 2]

6 echo $[${a} + ${b}]

7 }

8 fund

运行

chmod 777 ./test_yunsuan.sh

./test_yunsuan.sh

运行结果如下:

3

3

返回元祖

1 # /bin/bash

2 fund(){

3 a=1

4 b=2

5 echo $[1 + 2]

6 echo $[${a} + ${b}]

7 }

8 res=(`fund`)

9 echo ${res[*]}

10 echo ${res[0]}

11 echo ${res[1]}

运行结果如下

3 3

3

3

浮点数运算报错

1 # /bin/bash

2 fund(){

1 # /bin/bash

2 fund(){

3 a1=100.12

4 b1=200.3

5 result=$[$a1+$b1]

6 echo ${result}

7 }

8 fund

输出结果 报错误

./test_yunsuan.sh: line 5: 100.12+200.3: syntax error: invalid arithmetic operator (error token is ".12+200.3")

1 # /bin/bash

2 fund(){

3 a1=3

4 b1=2

5 result=$[$a1/$b1]

6 echo ${result}

7 }

8 fund

输出结果 相当于地板除,小数不会进行约等于,直接舍弃

1

方式二: bc计算器 支持浮点数运算

进行浮点数运算使用 bc 计算器

a = 10

b = 3

res=`echo "scale=2; $a / $b " | bc`

echo $res

输出结果是 3.33

scale是保留有效数字

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值