4、运算符


尚硅谷2022版Linux扩展篇Shell教程-讲师:武晟然

壁立千仞 无欲则刚

4、运算符

Shell无法在赋值时直接计算数字,默认使用的是字符串,想计算必须使用运算符。

4.1 expr

1)基本语法

expr[参数][参数][参数]

将后面要操作的数字和运算符当作参数传入。
2)案例实操:

# 5 - 2
[root@centos7-101 scripts]# expr 5 - 2
3
# 5 + 2
[root@centos7-101 scripts]# expr 5 + 2
7
# 5 * 2
[root@centos7-101 scripts]# expr 5 \* 2
10
# 6 / 2
[root@centos7-101 scripts]# expr 6 \/ 2
3
# 运算后赋值
[root@centos7-101 scripts]# a=$(expr 6 \/ 2 )
[root@centos7-101 scripts]# echo $a
3
# 运算后赋值
[root@centos7-101 scripts]# a=`expr 6 \/ 2`
[root@centos7-101 scripts]# echo $a
3

4.2 简化版

1)基本语法

“$((运算式))” 或 “$[运算式]”

中间不要有空格

2)案例实操:

计算(2+3)* 4 的值

# 5 - 2
[root@centos7-101 scripts]# echo $[5+2]
7
# 5 + 2
[root@centos7-101 scripts]# echo $[5-2]
3
# 5 * 2
[root@centos7-101 scripts]# echo $[5*2]
10
# 6 / 2
[root@centos7-101 scripts]# echo $[6/2]
3
# 运算后赋值
[atguigu@hadoop101 shells]# S=$[(2+3)*4]
[atguigu@hadoop101 shells]# echo $S

编写脚本 值1 + 值2 求和

[root@centos7-101 scripts]# touch add.sh
[root@centos7-101 scripts]# vim add.sh 
#!/bin/bash
sum=$[$1+$2]
echo sum=$sum

[root@centos7-101 scripts]# ./add.sh 29 31
sum=60
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值