歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> 關於Linux >> bash調試經驗

bash調試經驗

日期:2017/3/1 16:50:02   编辑:關於Linux
bash調試經驗 bash是Unix/Linux操作系統最常用的shell之一,它非常靈活,和awk、c++配合起來異常強大 www.2cto.com 以下使用一個測試腳本來說明使用bash調試的方法 www.2cto.com test.sh [plain] #!/bin/bash echo "----------------begin-----------------" awk '{sum+=1} END{print sum}' test.sh MAX=3 for ((i = 0; i < MAX; i++)) do loaddate=`date -d"-$i day" +%Y-%m-%d` echo $loaddate done echo "----------------end-----------------" 1. 使用bash -x bash -x打印出腳本執行過程中的所有語句 like: $ bash -x test.sh + echo ----------------begin----------------- ----------------begin----------------- + awk '{sum+=1} END{print sum}' test.sh 14 + MAX=3 + (( i = 0 )) + (( i < MAX )) ++ date '-d-0 day' +%Y-%m-%d + loaddate=2013-03-05 + echo 2013-03-05 2013-03-05 + (( i++ )) + (( i < MAX )) ++ date '-d-1 day' +%Y-%m-%d + loaddate=2013-03-04 + echo 2013-03-04 2013-03-04 + (( i++ )) + (( i < MAX )) ++ date '-d-2 day' +%Y-%m-%d + loaddate=2013-03-03 + echo 2013-03-03 2013-03-03 + (( i++ )) + (( i < MAX )) + echo ----------------end----------------- ----------------end----------------- 配合上注釋,bash -x基本可以滿足日常80%的需求 2. set 有的時候,我們的腳本非常復雜,使用bash -x得到的輸出太多,很難找到需要的信息 set 可以進行局部調試,在需要調試的代碼之前加上“set -x”,需要調試的代碼之後加上“set +x”即可 like: 修改test.sh: .... set -x awk '{sum+=1} END{print sum}' test.sh set +x ..... 運行: ----------------begin----------------- + awk '{sum+=1} END{print sum}' test.sh 16 + set +x 2013-03-05 2013-03-04 2013-03-03 ----------------end----------------- 3. 使用bash調試工具bashdb(Bash Debugger) bashdb是一個類GDB的調試工具,使用GDB的同學使用bashdb基本無障礙 bashdb可以運行斷點設置、變量查看等常見調試操作 bashdb需要單獨安裝 使用如下: $ bashdb --debug test.sh bash debugger, bashdb, release 4.2-0.8 Copyright 2002, 2003, 2004, 2006, 2007, 2008, 2009, 2010, 2011 Rocky Bernstein This is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. (/home/work/code/test.sh:3): 3: echo "----------------begin-----------------" bashdb<0> n #下一步 ----------------begin----------------- (/home/work/code/test.sh:5): 5: awk '{sum+=1} END{print sum}' test.sh bashdb<1> l #列出上下共10行代碼 1: #!/bin/bash 2: 3: echo "----------------begin-----------------" 4: 5: => awk '{sum+=1} END{print sum}' test.sh 6: 7: MAX=3 8: for ((i = 0; i < MAX; i++)) 9: do 10: loaddate=`date -d"-$i day" +%Y-%m-%d` bashdb<2> b 10 #第10行設置斷點 Breakpoint 1 set in file /home/work/code/test.sh, line 10. bashdb<3> c #繼續運行 14 Breakpoint 1 hit (1 times). (/home/work/code/test.sh:10): 10: loaddate=`date -d"-$i day" +%Y-%m-%d` bashdb<4> print $i #打印變量值 0 14: echo "----------------end-----------------"
Copyright © Linux教程網 All Rights Reserved