How to Debug a Shell Script

One of the most common questions asked by a new sysadmin or UNIX user is: How to debug a shell script?

Before proceeding further, let’s use the following sample script for this tutorial. The script is supposed to add two variables and print the result. Obviously, there is an error in the script and it will not print the expected result.

#!/bin/sh

one=1
two=2
result=""

results=<code>expr $one + $two</code>
echo result is $result

Now, let’s look at some of the shell script debugging techniques.

Shell Options -v, -x to Debug a Shell Script

The “-x” option is the easiest and one of the most common options to debug shell scripts. It will print the commands and their arguments as they are executed.

To print just the lines read by the shell, we can use the “-v” option.

You can also enable debugging by changing the default shebang line from:

to:

Debug a Portion Of a Shell Script

If you want to debug just a certain portion of a script, you can use the built-in set command to turn debugging on and off.

When the sript is run, you will get the following output.

Do you notice that after the “set +x” line, the debug statements have been turned off?

Custom Function to Debug Shell Script

This is usually my preferred way of debugging shell scripts. The idea is to add a variable that controls whether debugging is on or off. This variable is then checked in a custom function to print the relevant debug messages. Confused? Let’s look at an example.

Add a variable called “_debugmode” to the script. Set the variable to “1” if you want to turn on debugging.

Next, add a debugprint function to the script at the top of the script.

Once done, add debug statements wherever needed within the script.

Let’s look at the modified sample script with the custom debug function.

#!/bin/sh

_debugmode=1
one=1
two=2
result=&quot;&quot;

function debugprint ()
{
    [ $_debugmode -eq 1 ] &amp;&amp; echo &quot;debug: $@&quot;
}

results=<code>expr $one + $two</code>
debugprint &quot;result = $results&quot;
echo result is $result
debugprint &quot;End of script&quot;

The newly introduced code is highlighted. You will get the following output if you run the script with debugging on.

To turn off debugging, simply set _debugmode variable to “0“. You do not need to remove the debugprint function or the calls to the debugprint function.

ibrahim = { interested_in(unix, linux, android, open_source, reverse_engineering); coding(c, shell, php, python, java, javascript, nodejs, react); plays_on(xbox, ps4); linux_desktop_user(true); }