Shell中的基本运算符有:
- 算数运算符
- 关系运算符
- 逻辑运算符
- 字符串运算符
- 文件测试运算符
1、算数运算符
原生bash不支持简单的数学运算,需通过expr
[root@localhost~] a=1 b=2
[root@localhost~] echo `expr $a+$b`
1+2
[root@localhost~] echo `expr $a + $b`
3
注**
- 表达式和运算符之间要有空格,且这里是偏引号
另外,条件表达式要放在方括号之间,并且要有空格,例如: [$a==$b] 是错误的,必须写成 [$a == $b ]
- 关于shell中的[ ],是
执行基本的算数运算
:
[root@localhost~] a=1
[root@localhost~] b=2
[root@localhost~] echo $[a+b] $a+$b
3 1+2
运算符 | 备注 |
---|---|
+ – / % | 加减除取余 |
* | 需要转义,`expr $a * $b` |
= | 赋值,a=$b,变量b的值赋给a |
== | [ $a == $b ],返回false |
!= | [ $a != $b ],返回true |
[root@localhost~] echo `expr $a * $b`
expr: syntax error
[root@localhost~] echo `expr $a \* $b`
2
2、关系运算符
关系运算符只支持数字,不支持字符串,除非字符串的值是数字。
符号 | 作用 |
---|---|
-eq | 两边数值相等则为真 |
-ne | 两边数值不相等则为真 |
-gt | 大于则为真 |
-ge | 大于等于则为真 |
-lt | 小于则为真 |
-le | 小于等于则为真 |
举例:
[root@localhost~] vi test.sh
#!/bin/bash
a=1
b=2
if [ $a -eq -$b ]
then
echo 相等
else
echo 不等
fi
3、逻辑运算符
运算符 | 说明 |
---|---|
! | 非 !false为true |
-o | 或,一边为真则真 |
-a | 与,全真则真 |
|| | 逻辑或,出现一个true,则直接返回true,后面的表达式不执行 |
&& | 逻辑与,出现一个false,则直接返回false,后面的表达式则不执行 |
举例:
[root@localhost~] a=1 b=2
[root@localhost~] if [ $a -eq 1 -o $b -ne 1 ]
>then echo 666
>fi
666
[root@localhost~] if [[ $a -eq 1 || $b -ne 1 ]]
>then echo 666
>fi
666
4、字符串运算符
符号 | 作用 |
---|---|
= | 字符串相等为真 |
!= | 字符串不相等为真 |
-z 字符串 | 字符串长度为0则为真 |
-n 字符串 | 字符串长度不为0则为真 |
$字符串 | 检查字符串是否不为空,不为空返回true |
举例 :
[root@localhost~] s1=llg s2=llg2
[root@localhost~] if [ $s1=$2 ] =前后无空格,[]和expr的运算符有空格
>then
>echo equal
>else
>not equal
>fi
not equal
[root@localhost~] if [ -n $s1 ]
>then
>echo 1
>fi
1
[root@localhost~] if [ $s1 ] //注意空格
>then
>echo true
>fi
true
5、文件测试运算符
符号 | 作用 |
---|---|
-e fileName | 文件或目录存在时返回true |
-s fileName | 文件大小大于0KB时返回true |
-x fileName | 文件可执行时返回true |
-w fileName | 文件可写时返回true |
-r fileName | 文件可读时返回true |
-d fileName | 文件为目录时返回true |
-b fileName | 文件是块设备文件时返回true |
-c fileName | 文件是字符设备文件时返回true |
-L fileName | 检测文件是否存在并且是一个符号链接 |
[root@localhost] if [ -e /root/test.sh ]
>then
>echo 存在
>fi
存在
6、test指令搭配运算符
Shell中的test指令用于检查某个条件是否成立,可进行数值、字符、文件三个方面的检查。
数值test
举例:
[root@localhost~] vi test.sh
#!/bin/bash
a=1
b=2
if test $a -eq $b
then
echo 相等
else
echo 不等
fi
其中,if test $a -eq $b 也可写成 if [ $a -eq -$b ],不过后者注意方括号后面有个空格!
以上,注意test和 [ ] 的各自特点。
另外,除了if中应用,也可这样使用:
[root@localhost~] test -e /test.sh
这样执行结果并不会显示任何信息,稍作修改:
[root@localhost~] test -e /test.sh && echo exist || echo not exist
exist
[root@localhost~] test -e /test.sh; echo $?
0
对应于test的用法,[ ]也可这样用:
[root@localhost~] [ -e /test.sh ] ; echo $?
# 判断HOME变量是否为空
[root@localhost~] [ -z $HOME ] ;echo $?
1
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/146175.html