Linux Shell 腳本調試總結

Linux Shell 腳本調試總結

Shell腳本是用戶與Linux操作系統交互的一種方式,在腳本編程過程中自然少不了進行調試工作,本文將介紹三種常用的調試方法.(默認使用bash shell)

追蹤腳本的執行

使用-x選項可以打印出腳本執行的每一行命令以及當前狀態.
有如下腳本,打印數字1到10:

#!/bin/bash

for i in {1..10}
do
    echo $i
done

我們使用-x選項進行調試如下:

#在每一行前加上行號
export PS4='+${BASH_SOURCE}:${LINENO}:${FUNCNAME[0]}: '
#進行調試
sh -x test.sh 
#調試結果
+test.sh:3:: for i in '{1..10}'
+test.sh:5:: echo 1
1
+test.sh:3:: for i in '{1..10}'
+test.sh:5:: echo 2
2
+test.sh:3:: for i in '{1..10}'
+test.sh:5:: echo 3
3
+test.sh:3:: for i in '{1..10}'
+test.sh:5:: echo 4
4
+test.sh:3:: for i in '{1..10}'
+test.sh:5:: echo 5
5
+test.sh:3:: for i in '{1..10}'
+test.sh:5:: echo 6
6
+test.sh:3:: for i in '{1..10}'
+test.sh:5:: echo 7
7
+test.sh:3:: for i in '{1..10}'
+test.sh:5:: echo 8
8
+test.sh:3:: for i in '{1..10}'
+test.sh:5:: echo 9
9
+test.sh:3:: for i in '{1..10}'
+test.sh:5:: echo 10
10

有時候,你只需要對腳本的一部分進行調試,那麼可以使用如下命令:

set -x #在執行時顯示參數和命令
set +x #禁止調試
set -v #當命令行讀取時顯示輸入
set +v #禁止打印輸入

可以使用set builtin來啓用或者禁止調試打印.
對上文腳本做如下修改:

#!/bin/bash

for i in {1..10}
do
    set -x
    echo $i
    set +x
done

結果如下:

+test.sh:6:: echo 1
1
+test.sh:7:: set +x
+test.sh:6:: echo 2
2
+test.sh:7:: set +x
+test.sh:6:: echo 3
3
+test.sh:7:: set +x
+test.sh:6:: echo 4
4
+test.sh:7:: set +x
+test.sh:6:: echo 5
5
+test.sh:7:: set +x
+test.sh:6:: echo 6
6
+test.sh:7:: set +x
+test.sh:6:: echo 7
7
+test.sh:7:: set +x
+test.sh:6:: echo 8
8
+test.sh:7:: set +x
+test.sh:6:: echo 9
9
+test.sh:7:: set +x
+test.sh:6:: echo 10
10
+test.sh:7:: set +x

自定義日誌

上面這種調試手段是bash內建的,而且輸出格式固定而且繁瑣.所以我們需要根據需要的信息,自定義格式來顯示調試信息,通過設定_DEBUG環境變量來完成:

#!/bin/bash

# run:_DEBUG=on sh debug.sh

function DEBUG()
{
    [ "$_DEBUG" == "on" ] && $@ || :
}

for i in {1..5}
do
    DEBUG echo -e "This is debug line!"
    echo $i
done

我們將_DEBUG環境變量設定爲一個開關,只有打開時纔會輸出調試日誌.
使用如上腳本結果如下:

[aidu1602@ResU10 tools]$ _DEBUG=on sh debug.sh 
This is debug line!
1
This is debug line!
2
This is debug line!
3
This is debug line!
4
This is debug line!
5

這樣我們就可以自定義調試信息,並且可以控制調試開關啦.

使用專用調試器

如果你需要調試一個非常複雜的腳本,並且需要一個及其專業的調試器,像GDB那樣,那麼我推薦這款開源的腳本調試器bashdb,具體使用可以參考它的文檔.

反饋與建議

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章