if 命令的語法如下
if test-commands; then
consequent-commands;
[elif more-test-commands; then
more-consequents;]
[else alternate-consequents;]
fi
要注意的重點有兩個
1. if 判斷的是命令執行後的離開狀態 (exit status) 而不是命令的標準輸出 stdout
2. 因為離開狀態 (exit status) 為 0 表示成功,所以當 test-commands 的離開狀態為 0 時,if 會執行 consequent-commands。與 C 語言不同,C 語言是當 test-commands 為非 0 值時會執行 consequent-commands。
if 命令的官方資訊
範例:
#!/bin/sh
if declare -p var1 &>/dev/null; then
echo "The exit status of declare is $?"
echo "var1 is set"
else
echo "The exit status of declare is $?"
echo "var1 is unset"
fi
var1=
if declare -p var1 &>/dev/null; then
echo "The exit status of declare is $?"
echo "var1 is set"
else
echo "The exit status of declare is $?"
echo "var1 is unset"
fi
結果:
The exit status of declare is 1
var1 is unset
The exit status of declare is 0
var1 is set
好站連結
1. http://linux.vbird.org/linux_basic/0340bashshell-scripts.php#ifthen
沒有留言:
張貼留言