shell 中括号

来源:互联网 发布:域名注销流程 编辑:程序博客网 时间:2024/05/08 00:53

以下摘自ABS3.9.1中文版:
[[]]结构比[]结构更加通用。这是一个扩展的test命令,是从ksh88中引进的。
在[[和]]之间所有的字符都不会发生文件名扩展或者单词分割,但是会发生参数扩展和命令替换。
file=/etc/passwd
if [[ -e $file ]]
then
  echo "Password file exits."
fi
使用[[ ... ]] 条件判断结构,而不是[ ... ],能够防止脚本中的许多逻辑错误。比如,&&,||,<,和>操作符能够正常存在于[[ ]]条件判断结果中,但是如果出现在[ ]结构中的话,会报错。
在if后面也不一定非得是test命令或者是用于条件判断的中括号结构([ ]或[[ ]])。
dir=/test
if cd "$dir" 2>/dev/null;then echo "Now in $dir";else echo "Can't change to $dir";fi
if command 结构将会返回command的推出状态码。
与此相似,在中括号中的条件判断也不一定非得要if不可,也可以使用列表结构。
var1=20
var2=22
[ "$var1" -ne "$var2" ] && echo "$var1 is not equal to $var2"
home=/home/bozo
[ -d "$home" ] || echo "$home directory does not exist.
(( ))结构扩展并计算一个算术表达式的值. 如果表达式的结果为0, 那么返回的是"假". 而一个非零值的表达式所返回的退出状态码将为0, 或者是"true". 这的test命令和[ ]结构的行为正好相反.
例子 7-3. 算术测试需要使用(( ))
 # cat b.sh
#!/bin/bash

#算数测试

# (( ... ))结构可以用来计算并测试算术表达式的结果。
# 退出状态将会与[ ... ]结构完全相反!

(( 0 ))
echo "Exit status of \"(( 0 ))\" is $?."
(( 1 ))
echo "Exit status of \"(( 1 ))\" is $?."
(( 5 > 4 ))
echo "Exit status of \"(( 5 > 4 ))\" is $?."
(( 5 > 9 ))
echo "Exit status of \"(( 5 > 9 ))\" is $?."
(( 5 - 5 ))
echo "Exit status of \"(( 5 - 5 ))\" is $?."
(( 5 / 4 ))
echo "Exit status of \"(( 5 / 4 ))\" is $?."
(( 1 / 2 ))
echo "Exit status of \"(( 1 / 2 ))\" is $?."
(( 1 / 0 ))
#2>/dev/null
echo "Exit status of \"(( 1 / 0 ))\" is $?."
exit 0

# sh b.sh
Exit status of "(( 0 ))" is 1.
Exit status of "(( 1 ))" is 0.
Exit status of "(( 5 > 4 ))" is 0.
Exit status of "(( 5 > 9 ))" is 1.
Exit status of "(( 5 - 5 ))" is 1.
Exit status of "(( 5 / 4 ))" is 0.
Exit status of "(( 1 / 2 ))" is 1.
Exit status of "(( 1 / 0 ))" is 1.

去掉2>/dev/null后的结果是:
# sh b.sh
Exit status of "(( 0 ))" is 1.
Exit status of "(( 1 ))" is 0.
Exit status of "(( 5 > 4 ))" is 0.
Exit status of "(( 5 > 9 ))" is 1.
Exit status of "(( 5 - 5 ))" is 1.
Exit status of "(( 5 / 4 ))" is 0.
Exit status of "(( 1 / 2 ))" is 1.
b.sh: line 22: ((: 1 / 0 : division by 0 (error token is " ")
Exit status of "(( 1 / 0 ))" is 1.

呃。。。。好像说了一堆没啥用的东西。
简单来说就是[[]]支持&& ||> < 而[] 只支持test支持的条件判断。
[root@lwy test]# if [ $a == 1 -a $b == 3 ];then echo "OK" $a $b;fi
[root@lwy test]# if [ $a == 1 -o $b == 3 ];then echo "OK" $a $b;fi
OK 1 2
[root@lwy test]# if [ $a = 1 -a $b = 3 ];then echo "OK" $a $b;fi
[root@lwy test]# if [ $a = 1 -o $b = 3 ];then echo "OK" $a $b;fi
OK 1 2
[root@lwy test]# if [[ $a = 1 -o $b = 3 ]];then echo "OK" $a $b;fi
-bash: syntax error in conditional expression
-bash: syntax error near `-o'
[root@lwy test]# if [[ $a = 1 && $b = 3 ]];then echo "OK" $a $b;fi
[root@lwy test]# if [[ $a = 1 || $b = 3 ]];then echo "OK" $a $b;fi
OK 1 2