寫完腳本後,建議在運作腳本之前先檢查腳本中的文法,而不是檢視它們的輸出以确認它們是否正常工作。
<a target="_blank"></a>
在進入本指導的重點之前,讓我們簡要地探索下 verbose 模式。它可以用 <code>-v</code> 調試選項來啟用,它會告訴 shell 在讀取時顯示每行。
将下面内容輸入(或者複制粘貼)到一個檔案中。
<code>#!/bin/bash</code>
<code>#convert</code>
<code>for image in *.png; do</code>
<code>convert "$image" "${image%.png}.jpg"</code>
<code>echo "image $image converted to ${image%.png}.jpg"</code>
<code>done</code>
<code>exit 0</code>
接着儲存檔案,并用下面的指令使腳本可執行:
<code>$ chmod +x script.sh</code>
我們可以執行腳本并顯示它被 shell 讀取到的每一行:
<code>$ bash -v script.sh</code>
顯示shell腳本中的所有行
回到我們主題的重點,<code>-n</code> 激活文法檢查模式。它會讓 shell 讀取所有的指令,但是不會執行它們,它(shell)隻會檢查文法。
一旦 shell 腳本中發現有錯誤,shell 會在終端中輸出錯誤,不然就不會顯示任何東西。
激活文法檢查的指令如下:
<code>$ bash -n script.sh</code>
因為腳本中的文法是正确的,上面的指令不會顯示任何東西。是以,讓我們嘗試删除結束 for 循環的<code>done</code> 來看下是否會顯示錯誤:
下面是修改過的含有 bug 的批量将 png 圖檔轉換成 jpg 格式的腳本。
<code>#script with a bug</code>
儲存檔案,接着運作該腳本并執行文法檢查:
檢查 shell 腳本文法
從上面的輸出中,我們看到我們的腳本中有一個錯誤,for 循環缺少了一個結束的 <code>done</code> 關鍵字。shell 腳本從頭到尾檢查檔案,一旦沒有找到它(<code>done</code>),shell 會列印出一個文法錯誤:
<code>script.sh: line 11: syntax error: unexpected end of file</code>
我們可以同時結合 verbose 模式和文法檢查模式:
<code>$ bash -vn script.sh</code>
在腳本中同時啟用 verbose 檢查和文法檢查
另外,我們可以通過修改腳本的首行來啟用腳本檢查,如下面的例子:
<code>#!/bin/bash -n</code>
<code>#altering the first line of a script to enable syntax checking</code>
如上所示,儲存檔案并在運作中檢查文法:
<code>$ ./script.sh</code>
<code>script.sh: line 12: syntax error: unexpected end of file</code>
此外,我們可以用内置的 set 指令來在腳本中啟用調試模式。
下面的例子中,我們隻檢查腳本中的 for 循環文法。
<code>#using set shell built-in command to enable debugging</code>
<code>#enable debugging</code>
<code>set -n</code>
<code>#disable debugging</code>
<code>set +n</code>
再一次儲存并執行腳本:
總的來說,我們應該保證在執行 shell 腳本之前先檢查腳本文法以捕捉錯誤。
原文釋出時間為:2017-12-19
本文來自雲栖社群合作夥伴“linux中國”