先回顾一下Linux 中 if...else 的语法
if [ expression ]
then
Statement(s) to be executed if expression is true
fi
⚠️注意:这里的 expression 和中括号 [] 之间是有空格的,否则会报错!此外,变量两边都需要空格,千万不要吝啬!,例如 [[ 1 == 2 ]]的结果为“假”,但[[ 1==2 ]]的结果为“真”,后面一种显然是错的。
那么 [] 和 [[]] 的区别在哪儿呢?一句话概括的话就是只有单中括号 [ ] 是兼容 posix shell 标准的,而双方括号 [[]] 不兼容 posix shell 标准,而是 bash 特有的语法扩展。
具体的有下面的区别
[[]]用&&而不是-a表示逻辑与,用||而不是-o表示逻辑或
[[ 1 < 2 && b > a ]] && echo true || echo false
# true
[[ 1 < 2 -a b > a ]] && echo true || echo false
# bash: syntax error in conditional expression
# bash: syntax error near `-a’
[ 1 < 2 -a b > a ] && echo true || echo false
# true
[ 1 < 2 && b > a ] && echo true || echo false
# bash: 2: No such file or directory
# false
[]为shell命令,所以在其中的表达式应是它的命令行参数,所以串比较操作符>与<必须转义,否则就变成IO改向操作符了。[[]]中<与>不需转义
[ 2 \< 10 ] && echo true || echo false
# false
[ 2 -lt 10 ] && echo true || echo false
# true
[[ 2 < 10 ]] && echo true || echo false
# true
[[]]进行算术扩展,而[]不做
[[ 99+1 -eq 100 ]] && echo true || echo false
# true
[ 99+1 -eq 100 ] && echo true || echo false
# bash: [: 99+1: integer expression expected
# false
[ $((99+1)) -eq 100 ] && echo true || echo false
# true
[[]]能用正则,而[]不行
[ "test.php" == *.php ] && echo true || echo false
# false
[[ "test.php" == *.php ]] && echo true || echo false
# true
[[ "t.php" == [a-z].php ]] && echo true || echo false
# true
[ "test.php" == "*.php" ] && echo true || echo false
# false
[[ "test.php" == "*.php" ]] && echo true || echo false
# false
结论:尽量使用 [[]] 😂。
本文详细解析了Linux shell脚本中if...else语句的正确语法,包括expression的正确书写方式,以及[]与[[]]在条件测试中的区别。通过多个实例对比,阐述了两者在逻辑运算符、算术表达式、字符串比较和正则表达式支持方面的差异,建议读者在实际应用中尽量使用[[]]。
357

被折叠的 条评论
为什么被折叠?



