Even shell scripts may get very complex, so it is helpful to know how to debug them.

Lets explain it on a small example:

Executing it you’ll get an output like this:

To debug the execution of scripts the bash provides a debugging mode. There is one option -x to trace the execution

So you see, every line that is executed at the runtime will be printed with a leading + , comments are ignored. There is another option -v to enable verbose mode. In this mode each line that is read by the bash will be printed before it is executed:

Of course you can combine both modes, so the script is sequentially printed and the commands are traced:

These modes will help you to find some errors. To modify the output of the tracing mode you may configure the PS4 :

This will also print the file name of the executing script, the line number of the current command that is executed and the respective function name:

if You don’t want to trace a whole script you can enable/disable tracing from within a script:

This will result in something like:

It is of course also possible to enable/disable verbose mode inside the script with set -v and set +v , respectively.

You can actively support me!

anjan bacchu | Permalink |

thanks for the article.

Florian Heigl | Permalink |

Hi,

there’s two more things I love in debugging scripts:

set -n “parse it but don’t run it” (thats what I call as the first test of a new script) So, I very very often use this. The next one I only use rarely outside of debugging: set -e “exit on the first error” This can be interesting to catch errors that happen early in a script. Ideally, you handled all expected error scenarios and then set -e is catching on some more unexpected ones. Very naive people think it to be error handling if they put set -e in the start of a script, they are wrong ;) For debugging it’s definitely great. What other purposes? Very critical scripts that are better dead than doing anything unexpected AND also able to clean up their last run.

Give it a test next time :> And thanks for the wordpress Nagios check. Bye

export 'PS4=$\e[1;32m$\][Line: ${LINENO}]$\e[0m$\] :${FUNCNAME[0]}:'