How to debug shell scripts

How to debug shell scripts

In this tutorial I will show you, how to debug shell scripts.

Every bash coder should know how to debug its own scripts, in order to repair the unwanted mistakes.

The debugging mode can be activated inside the shell script, or used at invokation.

How to debug a bash script at invokation:

Syntax:  bash [debug options] script_name

Example: bash +xv scriptname

The -xv options are used for script debugging.
-x : display commands as they are executed

$ cat samplescript.sh
#!/bin/bash
echo 'hello'
$ bash -x samplescript.sh
+ echo hello
hello

-v : display input lines while they are read

$ bash -v samplescript.sh
#!/bin/bash
echo 'hello'
hello

-xv :

$ bash -xv samplescript.sh
#!/bin/bash
echo 'hello'
+ echo hello
hello

How to activate debug mode inside the script:

As I have said earlier, debugiing can be set inside the script.
The easiest way to do that is by addig the debug option in the shebang.

#!/bin/bash -x

This will activate debugging for the whole script. It is the same as invokating the script with: bash -x script_name.

You can also choose not to debug the entire script, with the command set:

The debugging will start from set -x and will stop at set +x .

$ cat samplescript.sh
#!/bin/bash
echo 'this is a sample script'
#debugging mode is not activated
set -x # set debug ON!
echo 'Hello'
set +x # set debug OFF!
# only the commands between set -x and set +x are debugged

Running the script:

$ bash samplescript.sh
this is a sample script
+ echo Hello
Hello
+ set +x

If you found this script usefull, use the next shell scripting article about shell variables.

Was this Tutorial helpful? Help others share on Facebook, Twitter, and Google Plus!

 
Enjoyed this video?
How to debug shell scripts
"No Thanks. Please Close This Box!"