
在進入主題前,先來認識一下 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
我們可以執行腳本,並顯示它被 shell 讀到的每一行:
$ bash -v script.sh

它會讓 shell 讀取所有命令但不執行,只做語法檢查。一旦發現錯誤,shell 會在終端輸出錯誤訊息,否則不顯示任何內容。
啟用命令如下:
$ bash -n script.sh
由於腳本語法正確,上面的命令不會顯示任何東西。因此我們試著刪掉結束 for 迴圈的 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

從輸出可見腳本有誤:for 迴圈缺少結束用的 done。shell 從頭到尾檢查檔案,找不到 done 便印出語法錯誤:
script.sh: line 11: syntax error: unexpected end of file
我們也可以同時結合 verbose 與語法檢查模式:
$ bash -vn script.sh

如下例:
#!/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 命令在腳本中啟用除錯。以下例子只檢查 for 迴圈的語法:
#!/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 腳本前,先檢查語法以捕捉錯誤,是個值得養成的好習慣。