使用通用流程建構元

為了控制程序檔的流程,外圍程序包含 whileifforcase 建構元。

If 控制指令

If 指令用於檢查運算式。例如,以下程式碼將測試目前的使用者是否為 Tux︰

if test $USER = "tux"; then
  echo "Hello Tux."
else
  echo "You are not Tux."
fi

測試運算式可以很複雜,也可以很簡單。下面的運算式會檢查檔案 foo.txt 是否存在︰

if test -e /tmp/foo.txt ;
then
  echo "Found foo.txt"
fi

測試運算式也可以縮寫到角括弧中︰

if [ -e /tmp/foo.txt ] ; then
  echo "Found foo.txt"
fi

如需更多有用的運算式,請參閱 http://www.cyberciti.biz/nixcraft/linux/docs/uniqlinuxfeatures/lsst/ch03sec02.html

使用 For 指令建立迴路

for 迴路可讓您對一組項目執行指令。例如,以下程式碼會列印目前目錄中關於 PNG 檔案的部分資訊︰

for i in *.png; do
 ls -l $i
done