how to debug a bash script

bash is used widely on linux system. We often made mistakes when writing bash script. Here are some tips for debugging a bash script.

1. add -x in #!/bin/bash  or bash -x myscript.sh

 

2. set -x #set trace on

  #commands

   set +x #set trace off

 

3. add -n in #!/bin/bash  or bash -n myscript.sh to eleminate syntax error without really executing the script

 

4. add a debug function

First, add a special variable called _DEBUG. Set _DEBUG 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 the DEBUG function as follows:
DEBUG echo "File is $filename"
OR
DEBUG set -x
Cmd1
Cmd2
DEBUG set +x

 

5. use bashdb

 

for more info please see:

http://www.cyberciti.biz/tips/debugging-shell-script.html

http://coolshell.cn/articles/1379.html

 http://wiki.bash-hackers.org/scripting/debuggingtips

你可能感兴趣的:(script)