shell腳本調試方法

咱們開啓了 Shell 腳本調試系列文章,先是解釋了不一樣的調試選項,下面介紹如何啓用 Shell 調試模式。web

寫完腳本後,建議在運行腳本以前先檢查腳本中的語法,而不是查看它們的輸出以確認它們是否正常工做。shell

在本系列的這一部分,咱們將瞭解如何使用語法檢查調試模式。記住咱們以前在本系列的第一部分中解釋了不一樣的調試選項,在這裏,咱們將使用它們來執行腳本調試。bash

啓用 verbose 調試模式ui

在進入本指導的重點以前,讓咱們簡要地探索下 verbose 模式。它能夠用 -v調試選項來啓用,它會告訴 shell 在讀取時顯示每行。spa

要展現這個如何工做,下面是一個示例腳原本批量將 PNG 圖片轉換成 JPG 格式。debug

將下面內容輸入(或者複製粘貼)到一個文件中。3d

#!/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 讀取到的每一行:code

$ bash -v script.sh

如何在 Shell 腳本中執行語法檢查調試模式

顯示shell腳本中的全部行blog

在 Shell 腳本中啓用語法檢查調試模式

回到咱們主題的重點,-n激活語法檢查模式。它會讓 shell 讀取全部的命令,可是不會執行它們,它(shell)只會檢查語法。

一旦 shell 腳本中發現有錯誤,shell 會在終端中輸出錯誤,否則就不會顯示任何東西。

激活語法檢查的命令以下:

$ bash -v script.sh

由於腳本中的語法是正確的,上面的命令不會顯示任何東西。因此,讓咱們嘗試刪除結束 for 循環的 done來看下是否會顯示錯誤:

下面是修改過的含有 bug 的批量將 png 圖片轉換成 jpg 格式的腳本。

#!/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 腳本語法

從上面的輸出中,咱們看到咱們的腳本中有一個錯誤,for 循環缺乏了一個結束的 done關鍵字。shell 腳本從頭至尾檢查文件,一旦沒有找到它(done),shell 會打印出一個語法錯誤:

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

咱們能夠同時結合 verbose 模式和語法檢查模式:

$ bash -vn script.sh

如何在 Shell 腳本中執行語法檢查調試模式

在腳本中同時啓用 verbose 檢查和語法檢查

另外,咱們能夠經過修改腳本的首行來啓用腳本檢查,以下面的例子:

#!/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 腳本以前先檢查腳本語法以捕捉錯誤。

請在下面的反饋欄中,給咱們發送關於這篇指導的任何問題或反饋。在這個系列的第三部分中,咱們會解釋並使用 shell 追蹤調試模式。

做者簡介:

Aaron Kili 是一個 Linux 及 F.O.S.S 熱衷者,即將是 Linux 系統管理員、web 開發者,目前是 TecMint 的內容創做者,他喜歡用電腦工做,並熱心分享知識。

做者:Aaron Kili[1] 譯者:geekpi校對:jasminepeng

本文由 LCTT[2] 原創編譯,Linux中國榮譽推出

相關文章
相關標籤/搜索