Pages

Saturday, July 13, 2013

how to debug bash shell script

 Unlike C/C++ applications, wherein you will you have to printf messages to debug, there is an easier and more detailed way of debugging shell scripts, specially in bash.

In your shell script, you can add

set -x

at the top of the script, this will make bash to print each command line it parse in your shell script, plus the result of the command as well.

Doing this permanently enable tracing, until you remove it or put "set +x" which is the default.

If you just want to see how it goes once, you can run your script "myscript.sh", try

$ bash -x myscript.sh

output looks like

+ var1=hi
+ var2='how are you'
++ paste hi how are you
paste: hi: No such file or directory
+ var3=
+ echo

"+" means, the sublevel of the command from the main shell script. i.e one + indicates the exact line of command as written in shell script, 2 +s indicate another command within the line of code you have written inside the script.

There is another, lesser debug info method.

$ bash -v myscript.sh

output looks like

#!/bin/bash
var1="hi"
var2="how are you"
var3=`paste $var1 $var2`
paste $var1 $var2
paste: hi: No such file or directory
echo $var3

This will just echo each line of the script as it parses, plus errors or echos from script if any.

No comments:

Post a Comment