• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Y-wee
博客园    首页    新随笔    联系   管理     

Shell运算符

Shell运算符

shell默认变量是字符串类型,所以变量之间做运算需要符合shell特定的规则

expr 运算式

通过expr可以计算表达式的值,注意运算式数字和符号之间必须要有空格

[root@zookeeper1 shell]# expr 2 + 3
5

# 特殊字符需要转义才能识别
[root@zookeeper1 shell]# expr 2 /* 3
expr: 语法错误
[root@zookeeper1 shell]# expr 2 \* 3
6

# 通过``将exp运算式的值赋给变量
[root@zookeeper1 shell]# result=`expr 2 + 3`
[root@zookeeper1 shell]# echo $result
5
# 通过$()将expr运算式的值赋给变量
[root@zookeeper1 shell]# result=$(expr 2 \* 3)
[root@zookeeper1 shell]# echo $result
6

$((运算式))

通过$((表达式))也可以得到运算式的值,并且特殊字符不用转义,运算式之间也可以不需要空格,值得注意的是,这种写法可以数字之间的比较可以直接使用<、<=、>、>=等

[root@zookeeper1 shell]# echo $((2+3))
5
[root@zookeeper1 shell]# result=$((2*3))
[root@zookeeper1 shell]# echo $result 
6

$[运算式]

通过$[运算式]也可以得到运算式的值,并且特殊字符不用转义,运算式之间也可以不需要空格,这种方式也是比较常用的

[root@zookeeper1 shell]# echo $[2+3]
5
[root@zookeeper1 shell]# result=$[2+3]
[root@zookeeper1 shell]# echo $result 
5

一个简单的脚本

新建add.sh脚本,内容如下:

[root@zookeeper1 shell]# cat add.sh 
#!/bin/bash

sum=$[$1+$2]
echo "sum=$sum"

执行脚本

[root@zookeeper1 shell]# ./add.sh 2 3
sum=5
记得快乐
posted @ 2022-04-23 22:19  Y-wee  阅读(38)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3