Shell中可以使用"[ ]"進行資料判斷,“[ ]”的用法跟test基本一致。
使用“[ ]”時要注意三點(來自鳥哥):
1、在中括弧"[]"內的每個組件都需要有空格鍵來分割。
2、在中括弧內的變數,最好都以雙引號括起來。
3、在中括弧內的常量,最好都以單引號或雙引號括起來
if else語句的結構為:
if [ condition ]; then
#some statements
elif [ condition ]; then
#some statements
else
#some statements
fi
下面是一個小例子,其中[ "$yn" == "Y" ] || [ "$yn" == "y" ] 等價於[ "$yn" == "Y" -o "$yn" == "y" ],“-o”表示“或”,串連兩個判斷。
#!/bin/bash#read user's input and do somethingread -p "please input (Y/N):" ynif [ "$yn" == "Y" ] || [ "$yn" == "y" ]; then echo "OK, you say yes."elif [ "$yn" == "N" ] || [ "$yn" == "n" ]; then echo "NO? goodbye."else echo "I don't know what you say"fi#test whether a directory exist,if not,create itif [ ! -d "keystoneclient" ]; then mkdir keystoneclientfi
while語句的基本結構為:
while [ condtion ]
do
#some statements
done
下面是一個小例子:
#!/bin/bashwhile [ "$yn" != "yes" -a "$yn" != "YES" ]do read -p "please input YSE or yes to stop this loop." yndoneecho "OK, you input the correct answer."
其中while語句中加入sleep語句可以構造一個簡單的計時器,sleep的單位是秒.如下面的例子,每隔一秒列印一下時間。
#!/bin/bashwhile [ 1 ]do date sleep 1done