bash在线调试工具:Bash 在线工具 | 菜鸟工具
字符串型比较符
比较符 | 含义 | 运算情况 |
== | 等于 | 相等返回 true |
!= | 不等于 | 不相等返回 true |
> | 大于(转换成ascii码再进行比较) | 大于返回 true |
>= | 大于等于,无法使用 | |
< | 小于(转换成ascii码再进行比较) | 小于返回 true |
<= | 小于等于,无法使用 | |
=~ | 包含 | 包含返回 true |
注意:使用双中括号[[]]
正确用法
#!/bin/bash
a="a"
b="b"
c="a"
d="d"
e="ab"
# 测试等于
if [[ $a == $c ]];then
echo "a=c"
fi
# 测试不等于
if [[ $a != $b ]];then
echo "a!=b"
fi
# 测试大于
if [[ $b > $a ]];then
echo "b>a"
fi
# 测试小于
if [[ $a < $b ]];then
echo "a<b"
fi
# 测试大于
if [[ $d > $b ]];then
echo "d>b"
fi
# 测试包含
if [[ $e =~ $b ]];then
echo "e=~b"
fi
运行结果
a=c
a!=b
b>a
a<b
d>b
e=~b
注意:字符串无法使用<=和>=进行比较,会报错
#!/bin/bash
a="a"
b="b"
c="c"
if [[ $c >= $a ]];then
echo "c>=a"
fi
if [[ $a <= $b ]];then
echo "a<=b"
fi
运行结果
script.sh: line 6: syntax error in conditional expression
script.sh: line 6: syntax error near `$a'
script.sh: line 6: `if [[ $c >= $a ]];then'
Exited with error status 2
添加转义也不行
#!/bin/bash
a="a"
b="b"
c="c"
# 添加转义
if [[ $c \>= $a ]];then
echo "c>=a"
fi
if [[ $a \<= $b ]];then
echo "a<=b"
fi
运行结果
script.sh: line 7: conditional binary operator expected
script.sh: line 7: syntax error near `\>='
script.sh: line 7: `if [[ $c \>= $a ]];then'
Exited with error status 2