Bash 指令稿入門
Alex Scriven
Data Scientist
當條件很多或複雜時,Case 陳述式通常比 IF 更合適。
假設你要測試以下條件與動作:
sydney,就把它移到 /sydney 目錄melbourne 或 brisbane,就刪除它canberra,就把它重新命名為 IMPORTANT_filename,其中 filename 是原始檔名你可以像這樣堆疊多個 IF:
grep 對第一個 ARGV 參數進行條件判斷。if grep -q 'sydney' $1; then
mv $1 sydney/
fi
if grep -q 'melbourne|brisbane' $1; then
rm $1
fi
if grep -q 'canberra' $1; then
mv $1 "IMPORTANT_$1"
fi
PATTERN 可用正規表示式。例如 Air* 表「以 Air 開頭」,*hat* 表「包含 hat」。基本 CASE 陳述式格式:
case 'STRINGVAR' inPATTERN1) COMMAND1;; PATTERN2) COMMAND2;;
*) DEFAULT COMMAND;;
esac 最後以關鍵字「esac」結尾
基本 CASE 陳述式格式:
case 'STRING' in PATTERN1) COMMAND1;; PATTERN2) COMMAND2;;*) DEFAULT COMMAND;;esac
我們先前的 IF:
if grep -q 'sydney' $1; then
mv $1 sydney/
fi
if grep -q 'melbourne|brisbane' $1; then
rm $1
fi
if grep -q 'canberra' $1; then
mv $1 "IMPORTANT_$1"
fi
我們新的 CASE:
case $(cat $1) in*sydney*) mv $1 sydney/ ;; *melbourne*|*brisbane*) rm $1 ;; *canberra*) mv $1 "IMPORTANT_$1" ;;*) echo "No cities found" ;; esac
Bash 指令稿入門