← Linux 與命令列
第 46 課,共 51 課 · 10 XP
條件判斷:if / elif / else
理論與題目說明
機器翻譯,尚未經母語人士審閱。
if 指令; then
...
elif 另一個指令; then
...
else
...
fi
if 確認的是指令的結束代碼:0 是真。[ … ] 只是一個回傳 0 或 1 的指令。所以 if 裡可以放任何指令:
if grep -q "^kai:" /etc/passwd; then
echo "the user kai exists"
fi
if ping -c1 -W1 8.8.8.8 > /dev/null 2>&1; then
echo "there is internet"
fi
if ! command -v git > /dev/null; then
echo "git isn't installed" >&2
exit 1
fi
then 可以放在 ; 之後的同一行(像上面那樣),或放在下一行。if 用單字 fi 結束——就是倒過來的 if。
>&2 把訊息輸出到錯誤串流,exit 1 以錯誤代碼結束腳本。
題目。 腳本的引數是路徑。是檔案就輸出 file(第二行輸出行數),是資料夾就輸出 dir,什麼都沒有就輸出 missing。每個測試開始前,起始程式碼都會建立 notes.txt(2 行)和資料夾 docs。