這是 Shell 腳本除錯系列的第二篇。第一篇介紹了各種除錯選項,這次談如何在執行前先做語法檢查。
寫完腳本後,建議先檢查語法,而不是直接跑一遍看輸出對不對——前者能在零風險下抓到結構性錯誤。
先認識 verbose 模式
verbose 模式用 -v 啟用,它會讓 shell 在讀取時把每一行顯示出來。以下用一個把 PNG 批次轉成 JPG 的腳本示範:
- #!/bin/bash
- #convert
- for image in *.png; do
- convert "$image" "${image%.png}.jpg"
- echo "image $image converted to ${image%.png}.jpg"
- done
- exit 0
存檔後加上執行權限:
- $ chmod +x script.sh
接著用 -v 執行,可以看到 shell 逐行讀取的過程:
- $ bash -v script.sh
啟用語法檢查模式
-n 才是這篇的主角。它讓 shell 讀完整份腳本卻不執行任何命令,只做語法驗證。一旦發現錯誤,shell 會在終端印出訊息;若語法正確,則完全不輸出任何內容。
- $ bash -n script.sh
因為上面的腳本語法正確,指令沒有任何回應。於是我們故意把結尾的 done 刪掉,做出一個有 bug 的版本:
- #!/bin/bash
- #script with a bug
- #convert
- for image in *.png; do
- convert "$image" "${image%.png}.jpg"
- echo "image $image converted to ${image%.png}.jpg"
- exit 0
存檔後再檢查一次:
- $ bash -n script.sh
這回 shell 從頭掃到尾都找不到 done,於是印出:
- script.sh: line 11: syntax error: unexpected end of file
兩個模式可以合用:
- $ bash -vn script.sh
另外也能直接改寫第一行的 shebang 來啟用檢查:
- #!/bin/bash -n
- #altering the first line of a script to enable syntax checking
- #convert
- for image in *.png; do
- convert "$image" "${image%.png}.jpg"
- echo "image $image converted to ${image%.png}.jpg"
- exit 0
存檔後直接執行就會看到同樣的錯誤訊息:
- $ ./script.sh
- script.sh: line 12: syntax error: unexpected end of file
最後還可以用內建的 set 指令,只針對腳本中的某一段啟用檢查:
- #!/bin/bash
- #using set shell built-in command to enable debugging
- #convert
- #enable debugging
- set -n
- for image in *.png; do
- convert "$image" "${image%.png}.jpg"
- echo "image $image converted to ${image%.png}.jpg"
- #disable debugging
- set +n
- exit 0
存檔並執行:
- $ ./script.sh
總結來說,執行 Shell 腳本前先做語法檢查,是捕捉錯誤成本最低的做法。系列第三篇將說明並實作 shell 追蹤(xtrace)除錯模式。