1. if 語句
read timeofday
if [ "$timeofday" = "yes" ] ;then #給$timeofday 加上“ ”的原因是,避免沒有任何輸入時,程序運行時報錯
echo "Good morning"
elif [ "$timeofday" = "no" ] ;then
echo "Good afternoon"
else
echo “Sorry ,$timeofday not recognized .Enter yes or no”
exit 1
fi
exit 0
2. for 語句
使用固定字符串的for循環:
for foo in bar fud 43 ; do
echo $foo
done
使用通配符擴展的for循環:
for file in $(ls f*.sh);do
echo $file
done
類C的for循環:
for ((i=1;i<=10;i++));do
echo -n "$i"
done
3.while語句
while [ "$strythis" != "secret"]; do
echo "Sorry ,try again"
read trythis
done
4.until 語句
until condition ;do
statements
done
5.case語句
case "$timeofday" in
yes | y | Yes | YES ) echo "Goog Morning";;
n* | N*) echo "Good Afternooon";;
*) echo "Sorry,answer not recognized"
echo "Please answer yes or no"
exit 1
;;
esac
6 命令列表
AND列表:
statement1 && statement2 && statement3 &&.....
從左開始順序執行每一條命令,如果一條命令返回的時ture,它右邊的下一條命令才能執行。如此持續直到有一條命令返回false,則結束
例如:
if [ -f file_one ] && echo "Hello" && [ -f file_two ] && echo "there" ; then#z注意,這個地方的執行類似於C語言的if語句執行,直到出現一個flase,就結束
echo "in if"
else
echo "in else"
fi
OR列表:
statement1 || statement2 || statement3 || ......
從左邊開始順序執行每條命令,如果一條命令返回的是flase,它右邊的下一條命令才能執行,如此執行知道有一條命令返回ture,或者列表中的所有命令都執行完畢
例如:
if [ -f file_one ] || echo "Hello" || echo " there" ;then
echo "in if"
else
echo "in else"