How to debug shell scripts

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

Watch Free Movies

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
echo 'hello'
$ bash -x
+ echo hello

-v : display input lines while they are read

$ bash -v
echo 'hello'

-xv :

$ bash -xv
echo 'hello'
+ echo 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
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
this is a sample script
+ echo Hello
+ set +x

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

Scroll to Top