Linux 愛好者園地

收集 Linux 與 Open Source Software 相關資訊與文件
小提示: 要快速找到需要的書籤嗎?點左側分類,畫面會先出現該分類下相關的標籤雲。再點標籤之後,即會幫你精準找到「分類」+「標籤」交集過後的書籤。也可以用下方功能列中之收推、討論或熱門等方式加以排序喔
瀏覽模式
書籤標題
收藏時間
434097

checko 收藏於 2007/01/30

Q. How can I Debug a shell scripts? A. This is most common question asked by new admins or UNIX user. Shell scripting debugging can be boring job (read as not easy). There are various ways to debug a shell script. Method # 1: Use -x option Run a shell script with -x option. $ bash -x script-name $ bash -x domains.sh Method # 2: Use of set builtin command Bash shell offers debugging options which can be turn on or off using set command. => set -x : Display commands and their arguments as they are executed. => set -v : Display shell input lines as they are read. You can use above two command in shell script itself: #!/bin/bash clear # turn on debug mode set -x for f in * do file $f done # turn OFF debug mode set +x ls # more commands You can replace standard #!/bin/bash with (for debugging) #!/bin/bash -xv Method # 3: Use of intelligent DEBUG function Add special variable _DEBUG. Set to `on’ when you need to debug a script: _DEBUG="on" Put the following function at the beginning of the script: function DEBUG() { [ "$_DEBUG" == "on" ] && $@ || : } Now wherever you need debugging simply use DEBUG function DEBUG echo "File is $filename" OR DEBUG set -x Cmd1 Cmd2 DEBUG set +x When debugging done and before moving a script to production set _DEBUG to off No need to delete debug lines. _DEBUG="off" # set to anything but not to 'on' Sample script: #!/bin/bash _DEBUG="on" function DEBUG() { [ "$_DEBUG" == "on" ] && $@ || : } DEBUG echo 'Reading files' for i in * do grep 'something' $i > /dev/null [ $? -eq 0 ] && echo "Found in $i file" || : done DEBUG set -x a=2 b=3 c=$(( $a + $b )) DEBUG set +x echo "$a + $b = $c" Save and run the script: $ ./script.sh Output: Reading files Found in xyz.txt file + a=2 + b=3 + c=5 + DEBUG set +x + '[' on == on ']' + set +x 2 + 3 = 5 Now set DEBUG to off _DEBUG="off" Run script: $ ./script.sh Output: Found in xyz.txt file 2 + 3 = 5 Above is a simple but quite effective technique. You can also try to use DEBUG as an alias instead of function.

完整
2007/01/30
318108

letoh 收藏於 2006/11/09

完整
2006/11/09
308061

letoh 收藏於 2006/10/30

完整
2006/10/30
197607

checko 收藏於 2006/09/30

清楚的範例,使用find

完整
2006/09/30