Stories

Detail Return Return

Linux Bash Shell 調試技巧 - Stories Detail

How to Debug Linux Bash Shell Script

在大多數編程語言中,都有調試工具可用於調試。調試器是一種可以運行程序或腳本的工具,它使您能夠在腳本或程序運行時檢查其內部結構。

在這篇文章中,我們將學習如何在 linux 中逐行調試 bash shell 腳本。在 shell 腳本中,我們沒有任何調試工具,但是在 bash 命令行選項 (如 -n, -v ,-x) 的幫助下,我們可以進行調試。

檢查 Shell 腳本語法錯誤

當我們在 bash 命令中使用 -n 選項運行腳本時,它不會執行腳本,但它會讀取腳本並驗證語法,如果有錯誤,則會報告錯誤。

讓我們創建一個包含以下內容的腳本

$ vi debug_quotes.sh
#!/bin/bash
echo "USER=$USER"
echo "Today's Date: $(date)
echo "SHELL=$SHELL"

保存並關閉該文件。

現在嘗試使用 -n 選項運行腳本

$ bash -n debug_quotes.sh
debug_quotes.sh: line 4: unexpected EOF while looking for matching `"'
debug_quotes.sh: line 5: syntax error: unexpected end of file
$

上面的輸出顯示有語法錯誤,缺少雙引號。要解決這個問題,在顯示今天日期的行尾加上雙引號。

Debug-Quotes-Shell-Script-Linux

以詳細模式運行 Shell 腳本

bash 命令中的 -v 選項告訴 shell 腳本以詳細模式運行。實際上,這意味着 shell 將在執行命令之前回顯每個命令。這是非常有用的,因為它通常可以幫助找到錯誤。

讓我們創建一個名為 listusers.sh 的 shell 腳本,其中包含以下內容

$ vi listusers.sh
#!/bin/bash
cut -d : -f1,5,7 /etc/passwd | grep -v sbin | grep sh | sort > /tmp/users.txt
awk -F':' ' { printf ( "%-12s %-40s\n", $1, $2 ) } ' /tmp/users.txt

#Clean up the temporary file.
/bin/rm -f /tmp/users.txt

使用 -v 選項執行腳本

$ bash -v listusers.sh

list-users-script-output-linux

在上面的輸出中,腳本輸出與執行的命令混合在一起。但是,使用 -v 選項,至少您可以更好地瞭解 shell 在運行腳本時正在做什麼。

使用 -n 和 -v 選項運行腳本

我們可以組合使用 -n-v 命令行選項,這是一個很好的組合,因為我們可以在查看腳本輸出的同時檢查腳本的語法。

讓我們回顧思考之前使用的腳本“debug_quotes.sh”

$ bash -nv debug_quotes.sh
#!/bin/bash
echo "USER=$USER"
echo "Today's Date: $(date)
echo "SHELL=$SHELL"
debug_quotes.sh: line 4: unexpected EOF while looking for matching `"'
debug_quotes.sh: line 5: syntax error: unexpected end of file
$

逐行調試 shell 腳本

-x 選項是 execution trace 的縮寫,它告訴 shell 在執行替換步驟後回顯每個命令。因此,我們可以看到變量和命令的值。通常,這個選項本身將有助於診斷問題。

在大多數情況下,-x 選項提供了關於腳本的最有用的信息,但它可能導致大量輸出。

$ bash -x listusers.sh
+ sort
+ grep sh
+ grep -v sbin
+ cut -d : -f1,5,7 /etc/passwd
+ awk -F: ' { printf ( "%-12s %-40s\n", $1, $2 ) } ' /tmp/users.txt
linuxtechi linuxtechi,,,
root root
+ /bin/rm -f /tmp/users.txt
$

正如我們所看到的,shell 在每個命令前面插入了一個 + 號。

使用 ShellCheck 調試 Shell 腳本

Shellcheck 是一個免費的工具,它為我們的 bash 或 shell 腳本提供警告和建議,指出了 shell 腳本的語法和語義問題。

Ubuntu / Debian 安裝

$ sudo apt install shellcheck

RHEL / Fedora / CentOS 安裝

$ sudo dnf install epel-release -y
$ sudo dnf install ShellCheck

使用 shellcheck 運行上面的 debug_quotes.sh 腳本

$ shellcheck debug_quotes.sh

ShellCheck-Script-Output

要抑制警告消息,請使用 -e 選項,如下所示

$ shellcheck -e SC1078 debug_quotes.sh

Exclude-Warning-Shellscheck-Script

上面的輸出確認第 3 行有語法錯誤,如果我們在第 3 行末尾加上雙引號,那麼語法錯誤將被修復。

我的開源項目

酷瓜雲課堂-開源知識付費解決方案

  • course-tencent-cloud(酷瓜雲課堂 - gitee倉庫)
  • course-tencent-cloud(酷瓜雲課堂 - github倉庫)
user avatar greatsql Avatar sysin Avatar guoduandemuer Avatar jianshendemifan Avatar shiluodexiaomaju Avatar
Favorites 5 users favorite the story!
Favorites

Add a new Comments

Some HTML is okay.