Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Shell 程式設計

Shell 腳本除錯(二):用語法檢查模式先抓錯再執行

這是 Shell 腳本除錯系列的第二篇。第一篇介紹了各種除錯選項,這次談如何在執行前先做語法檢查。

寫完腳本後,建議先檢查語法,而不是直接跑一遍看輸出對不對——前者能在零風險下抓到結構性錯誤。

先認識 verbose 模式

verbose 模式用 -v 啟用,它會讓 shell 在讀取時把每一行顯示出來。以下用一個把 PNG 批次轉成 JPG 的腳本示範:

  1. #!/bin/bash 
  2. #convert 
  3. for image in *.png; do 
  4. convert  "$image"  "${image%.png}.jpg" 
  5. echo "image $image converted to ${image%.png}.jpg" 
  6. done 
  7. exit 0 

存檔後加上執行權限:

  1. $ chmod +x script.sh 

接著用 -v 執行,可以看到 shell 逐行讀取的過程:

  1. $ bash -v script.sh  

啟用語法檢查模式

-n 才是這篇的主角。它讓 shell 讀完整份腳本卻不執行任何命令,只做語法驗證。一旦發現錯誤,shell 會在終端印出訊息;若語法正確,則完全不輸出任何內容。

  1. $ bash -n script.sh 

因為上面的腳本語法正確,指令沒有任何回應。於是我們故意把結尾的 done 刪掉,做出一個有 bug 的版本:

  1. #!/bin/bash 
  2. #script with a bug 
  3. #convert 
  4. for image in *.png; do 
  5. convert  "$image"  "${image%.png}.jpg" 
  6. echo "image $image converted to ${image%.png}.jpg" 
  7. exit 0 

存檔後再檢查一次:

  1. $ bash -n script.sh  

這回 shell 從頭掃到尾都找不到 done,於是印出:

  1. script.sh: line 11: syntax error: unexpected end of file 

兩個模式可以合用:

  1. $ bash -vn script.sh  

另外也能直接改寫第一行的 shebang 來啟用檢查:

  1. #!/bin/bash -n 
  2. #altering the first line of a script to enable syntax checking 
  3. #convert 
  4. for image in *.png; do 
  5. convert  "$image"  "${image%.png}.jpg" 
  6. echo "image $image converted to ${image%.png}.jpg" 
  7. exit 0 

存檔後直接執行就會看到同樣的錯誤訊息:

  1. $ ./script.sh 
  2. script.sh: line 12: syntax error: unexpected end of file 

最後還可以用內建的 set 指令,只針對腳本中的某一段啟用檢查:

  1. #!/bin/bash 
  2. #using set shell built-in command to enable debugging 
  3. #convert 
  4. #enable debugging 
  5. set -n 
  6. for image in *.png; do 
  7. convert  "$image"  "${image%.png}.jpg" 
  8. echo "image $image converted to ${image%.png}.jpg" 
  9. #disable debugging 
  10. set +n 
  11. exit 0 

存檔並執行:

  1. $ ./script.sh 

總結來說,執行 Shell 腳本前先做語法檢查,是捕捉錯誤成本最低的做法。系列第三篇將說明並實作 shell 追蹤(xtrace)除錯模式。

Copyright © Linux教程網 All Rights Reserved