2011年12月7日水曜日

[Shell 基础] if 条件判断语句

1. 基本语法
if true
then
fi

if true; then
fi

if true; then
else
fi

if true; then
elif true; then
else
fi

if test true; then
fi

if [ true ]; then
fi


2. AND 条件
if test "a" = "a" -a 1 -eq 1; then
fi

if [ "a" = "a" -a 1 -eq 1 ]; then
fi

if test "a" = "a" && [ 1 -eq 1 ]; then
fi

if test "a" = "a" && test 1 -eq 1 test; then
fi

if [ "a" = "a" ] && [ 1 -eq 1 ]; then
fi

3. OR 条件
if test "a" = "a" -o 1 -eq 1; then
fi

if [ "a" = "a" -o 1 -eq 1 ]; then
fi

if test "a" = "a" || [ 1 -eq 1 ]; then
fi

if test "a" = "a" || test 1 -eq 1 test; then
fi

if [ "a" = "a" ] || [ 1 -eq 1 ]; then
fi

4. AND 条件和 OR 条件
if test "a" = "a" -a 1 -eq 1 -o true; then
fi

if [ "a" = "a" ] && [ 1 -eq 1 ] || [ true ]; then
fi

5. 加括号 () 改变执行顺序
5-1. -a -o 连接时
test \( 1 = 1 -o 1 -ne 1 \) -a 2 != 2; echo $?

5-2. && || 连接时括号不必指定 \
[ 1 = 1 ] && ( [ 1 -eq 1 ] || [ 2 -ne 2 ] ); echo $?

5-3. 可以用{}, 此时必须在 } 结束前加 ;
[ 1 = 1 ] && { [ 1 -eq 1 ] || [ 2 -ne 2 ]; }; echo $?


6. NOT
! [ 1 -eq 1 ]; echo $? # 1
!([ 1 -eq 1 ]); echo $? # 1

7. [] 和 [[ ]] 的区别
7-1. [ 是 /usr/bin/ 下的命令
$ which [
/usr/bin/[

$ which [[
$

7-2. 对于错误信息的处理
$ unset hoge
$ [ $hoge = "HOGE" ] # 打印出错误信息
-bash: [: =: unary operator expected

$ [[ $hoge = "HOGE" ]] # 忽略错误信息
$

7-3. 结束状态也不同
$ unset hoge
$ [ $hoge = "HOGE" ]
-bash: [: =: unary operator expected
$ echo $?
2

$ [[ $hoge = "HOGE" ]]
$ echo $?
1

0 件のコメント:

コメントを投稿