1、
條件判斷式:
if [ 條件判斷式 ]; then
當(dāng)條件判斷式成立時(shí),可以進(jìn)行的指令工作內(nèi)容;
fi
|
if [ 條件判斷式 ]; then
當(dāng)條件判斷式成立時(shí),可以進(jìn)行的指令工作內(nèi)容;
else
當(dāng)條件判斷式不成立時(shí),可以進(jìn)行的指令工作內(nèi)容;
fi
|
如果考慮更復(fù)雜的情況,則可以使用這個(gè)語法:
if [ 條件判斷式一 ]; then
當(dāng)條件判斷式一成立時(shí),可以進(jìn)行的指令工作內(nèi)容;
elif [ 條件判斷式二 ]; then
當(dāng)條件判斷式二成立時(shí),可以進(jìn)行的指令工作內(nèi)容;
else
當(dāng)條件判斷式一與二均不成立時(shí),可以進(jìn)行的指令工作內(nèi)容;
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 $變數(shù)名稱 in
"第一個(gè)變數(shù)內(nèi)容")
程式段
;;
"第二個(gè)變數(shù)內(nèi)容")
程式段
;;
*)
不包含第一個(gè)變數(shù)內(nèi)容與第二個(gè)變數(shù)內(nèi)容的其他程式執(zhí)行段
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 的設(shè)定一定要在程式的最前面
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
|
當(dāng) condition 條件成立時(shí),就進(jìn)行循環(huán),直到 condition 的條件不成立才停止。
until [ condition ]
do
程式段落
done
|
當(dāng) condition 條件成立時(shí),就終止循環(huán), 否則就持續(xù)進(jìn)行。
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 (( 初始值; 限制值; 執(zhí)行步階 ))
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循環(huán)不止用在數(shù)字的循環(huán),非數(shù)字也是可以的:
for $var in con1 con2 con3 ...
do
程式段
done
|
for animal in dog cat elephant
do
echo "There are ""$animal""s.... "
done
|
復(fù)雜一點(diǎn)的:
# 1. 先看看這個(gè)目錄是否存在?。?/span>
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. 開始測(cè)試檔案啰~
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
|