Bash 指令稿入門
Alex Scriven
Data Scientist
Bash 中基本的 IF 陳述式結構如下:
if [ CONDITION ]; then# SOME CODEelse # SOME OTHER CODEfi
兩個小技巧:
];我們可以在 IF 陳述式中做基本字串比較:
x="Queen"if [ $x == "King" ]; thenecho "$x is a King!"else echo "$x is not a King!" fi
Queen is not a King!
你也可以用 != 表示「不等於」
算術 IF 陳述式可使用雙括號結構:
x=10if (($x > 5)); then echo "$x is more than 5!" fi
10 is more than 5!
算術 IF 也可用中括號加算術旗標,而非使用(>, <, =, != 等):
-eq 表示「等於」-ne 表示「不等於」-lt 表示「小於」-le 表示「小於或等於」-gt 表示「大於」-ge 表示「大於或等於」以下用中括號符號重現上一個例子:
x=10
if [ $x -gt 5 ]; then
echo "$x is more than 5!"
fi
10 is more than 5!
Bash 也提供多種與檔案相關的旗標,例如:
-e 檔案存在-s 檔案存在且大小大於 0-r 檔案存在且可讀-w 檔案存在且可寫還有其他多種:
在 Bash 中要結合條件(AND)或使用 OR,可用下列符號:
&& 表示 AND|| 表示 OR在 Bash 中,你可以這樣串接多個條件:
x=10
if [ $x -gt 5 ] && [ $x -lt 11 ]; then
echo "$x is more than 5 and less than 11!"
fi
或使用雙重中括號符號:
x=10
if [[ $x -gt 5 && $x -lt 11 ]]; then
echo "$x is more than 5 and less than 11!"
fi
你也可以直接在條件中使用許多指令列程式,並且「移除中括號」。
例如,若 words.txt 檔案內含有 'Hello World!':
if grep -q Hello words.txt; then
echo "Hello is inside!"
fi
Hello is inside!
你也可以在條件中呼叫巢狀 shell(shell 中再啟一個 shell)。
我們把上一個例子改寫如下,結果相同:
if $(grep -q Hello words.txt); then
echo "Hello is inside!"
fi
Hello is inside!
Bash 指令稿入門