1、條件判斷式:
    
if [ 條件判斷式 ]; then
當條件判斷式成立時,可以進行的指令工作內容;
fi

if [ 條件判斷式 ]; then
當條件判斷式成立時,可以進行的指令工作內容;
else
當條件判斷式不成立時,可以進行的指令工作內容;
fi
如果考慮更復雜的情況,則可以使用這個語法:
if [ 條件判斷式一 ]; then
當條件判斷式一成立時,可以進行的指令工作內容;
elif [ 條件判斷式二 ]; then
當條件判斷式二成立時,可以進行的指令工作內容;
else
當條件判斷式一與二均不成立時,可以進行的指令工作內容;
fi
    shell舉例:
read -p "Please input (Y/N): " yn
if [ "$yn" == "Y" ] || [ "$yn" == "y" ]; then
echo "OK, continue"
elif [ "$yn" == "N" ] || [ "$yn" == "n" ]; then
echo "Oh, interrupt!"
else
echo "I don't know what is your choise"
fi


2、利用 case ..... esac 判斷

case $變數名稱 in
"第一個變數內容")
程式段
;;
"第二個變數內容")
程式段
;;
*)
不包含第一個變數內容與第二個變數內容的其他程式執行段
exit 1
;;
esac

case $1 in
"hello")
echo "Hello, how are you ?"
;;
"")
echo "You MUST input parameters, ex> $0 someword"
;;
*)
echo "Usage $0 {hello}"
;;
esac


3、利用 function 功能
function fname() {
程式段
}
    注意:function 的設定一定要在程式的最前面

function printit(){
echo "Your choice is $1"
}
echo "This program will print your selection !"
case $1 in
"one")
printit 1
;;
"two")
printit 2
;;
"three")
printit 3
;;
*)
echo "Usage {one|two|three}"
;;
esac


4、loop    
while [ condition ]
do

程式段落
done
當 condition 條件成立時,就進行循環,直到 condition 的條件不成立才停止
until [ condition ]
do

程式段落
done
當 condition 條件成立時,就終止循環, 否則就持續進行。

while [ "$yn" != "yes" ] && [ "$yn" != "YES" ]
do
read -p "Please input yes/YES to stop this program: " yn
done


until [ "$yn" == "yes" ] || [ "$yn" == "YES" ]
do
read -p "Please input yes/YES to stop this program: " yn
done


5、for...do....done

for (( 初始值; 限制值; 執行步階 ))
do

程式段
done

s=0
for (( i=1; i<=100; i=i+1 ))
do
s=$(($s+$i))
done
echo "The result of '1+2+3+...+100' is ==> $s"


for循環不止用在數字的循環,非數字也是可以的:
for $var in con1 con2 con3 ...
do
程式段
done

for animal in dog cat elephant
do
echo "There are ""$animal""s.... "
done


復雜一點的:
# 1. 先看看這個目錄是否存在啊?
read -p "Please input a directory: " dir
if [ "$dir" == "" ] || [ ! -d "$dir" ]; then
echo "The $dir is NOT exist in your system."
exit 1
fi
# 2. 開始測試檔案啰~
filelist=`ls $dir`
for filename in $filelist
do
perm=""
test -r "$dir/$filename" && perm="$perm readable"
test -w "$dir/$filename" && perm="$perm writable"
test -x "$dir/$filename" && perm="$perm executable"
echo "The file $dir/$filename's permission is $perm "
done