Skip to content
ImagineWorld

Debugging Shell Scripts

node_idnode-book_the-ultimate-linux-shell-scripting-guide_chapter-21-debugging-shell-scripts
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num21
chapter_titleDebugging Shell Scripts
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

If you’ve ever written a beautiful looking script, only to be disappointed when it doesn’t work properly, don’t feel alone. This happens to all of us, and even happened to me a few times when I was creating scripts for this book. (I know, shocking, right?)

The debugging process should begin the moment that you begin to design your code. Put careful thought into the design, test each portion as you write it, and—for goodness’ sake—use a text editor with color-coded syntax highlighting. (That color highlighting will prevent you from making a multitude of typographical errors.)

Topics in the chapter include:

  • Understanding common scripting errors
  • Not Enough Quoting
  • Creating a Wild Loop
  • Using shell script debugging tools and techniques
  • Using echo Statements
  • Using xtrace for Debugging
  • Checking for Undefined Variables
  • Checking for Errors with the -e Option
  • Using bash Debugger
  • Debugging a script with bashdb
  • Getting help with bashdb

If you’re ready, let’s get started.

Technical Requirements

For this chapter, I’m mainly just using the Fedora workstation that I’m using to create this Word file. But, you can use whichever Linux virtual machine that you like, as long as it has a desktop environment installed. (One of the demos requires a desktop.)

For the final topic, I’ll show you how to install and use bashdb on Debian/Ubuntu, Fedora, FreeBSD, and macOS.

As always, you can grab the scripts by doing:

git clone https://github.com/PacktPublishing/The-Ultimate-Linux-Shell-Scripting-Guide.git

The most important step in debugging is understanding the common errors that could cause your scripts to either outright fail, or to give you incorrect results. Let’s look at a few examples.

You can have a few different problems if you don’t surround variable names with quotes. Here are some examples.

For this demo, I’ve moved into an empty directory in order to keep the files I’ll be creating separate from the files in my main home directory. I want to create some files with a timestamp in the filename. To do that, I’ll use the date command, without any option switches.

First, I’ll create a file from the command-line using touch:

Terminal window
donnie@fedora:~/quoting_demo$ touch somefile_$(date).txt
donnie@fedora:~/quoting_demo$

Okay, let’s look at the file:

Terminal window
donnie@fedora:~/quoting_demo$ ls -l
total 0
-rw-r--r--. 1 donnie donnie 0 Aug 20 15:08 03:08:51
-rw-r--r--. 1 donnie donnie 0 Aug 20 15:08 20
-rw-r--r--. 1 donnie donnie 0 Aug 20 15:08 2024.txt
-rw-r--r--. 1 donnie donnie 0 Aug 20 15:08 Aug
-rw-r--r--. 1 donnie donnie 0 Aug 20 15:08 EDT
-rw-r--r--. 1 donnie donnie 0 Aug 20 15:08 PM
-rw-r--r--. 1 donnie donnie 0 Aug 20 15:08 somefile_Tue
donnie@fedora:~/quoting_demo$

Whoa, now. What’s going on here? Instead of having one file, I have seven. Each file has a portion of the current date in its filename. Well, the problem is that date, without any option switches, produces output with blank spaces in it, like this:

Terminal window
donnie@fedora:~/quoting_demo$ date
Tue Aug 20 03:13:23 PM EDT 2024
donnie@fedora:~/quoting_demo$

So when the shell saw those blank spaces, it thought that I wanted to create multiple files, instead of just one. Let’s delete all of these files, and try this again with some quotes:

Terminal window
donnie@fedora:~/quoting_demo$ touch somefile_"$(date)".txt
donnie@fedora:~/quoting_demo$ ls -l
total 0
-rw-r--r--. 1 donnie donnie 0 Aug 20 15:15 'somefile_Tue Aug 20 03:15:37 PM EDT
2024.txt'
donnie@fedora:~/quoting_demo$

You see how I’ve surrounded the command substitution construct with a pair of double quotes, which causes the shell to ignore the blank spaces. So now, I have just one file with the correct filename.

Problems with Unset Variables

For our next scenario, let’s look at the quote_problem1.sh script:

#!/bin/bash
number=1
if [ $number = 1 ]; then
echo "Number equals 1"
else
echo "Number does not equal 1"
fi

All it does is to tell us whether or not the value of number is 1. Running the script looks like this:

Terminal window
donnie@fedora:~$ ./quote_problem1.sh
Number equals 1
donnie@fedora:~$

Okay, it works fine. Now, I’ll edit the file to change the value of number to 2, and run the script again. Here’s how that looks:

Terminal window
donnie@fedora:~$ ./quote_problem1.sh
Number does not equal 1
donnie@fedora:~$

Now, let’s try that with an unset variable, as you see in quote_problem2.sh:

#!/bin/bash
number=
if [ $number = 1 ]; then
echo "Number equals 1"
else
echo "Number does not equal 1"
fi

When we say that a variable is unset, it just means that we defined the variable, but haven’t assigned a value to it. Let’s see what happens when I try to run this script.

Terminal window
donnie@fedora:~$ ./quote_problem2.sh
./quote_problem2.sh: line 4: [: =: unary operator expected
Number does not equal 1
donnie@fedora:~$

The problem is that the if [ number=1]testislookingforsomesortofvalueforthenumbervariable.But,numberhasnovalue,whichbreaksthetest.Fortunately,it′saneasyfix.AllI′llhavetodoistosurroundthenumber = 1 ] test is looking for some sort of value for the number variable. But, number has no value, which breaks the test. Fortunately, it's an easy fix. All I'll have to do is to surround the number that’s in the test statement with a pair of double quotes, as you see in quote_problem3.sh:

#!/bin/bash
number=
if [ "$number" = 1 ]; then
echo "Number equals 1"
else
echo "Number does not equal 1"
fi

Running this script will show the correct results:

Terminal window
donnie@fedora:~$ ./quote_problem3.sh
Number does not equal 1
donnie@fedora:~$

This works because instead of having no value at all as we had before, number now effectively has the value of a blank space. A blank space isn’t equal to 1, so the script works.

It’s normally better to always assign an initial value to your variables as you create them, in order to prevent these kinds of problems. However, it’s sometimes desirable to use an unset variable. For example, you might want your script to do one thing if a variable is unset, or to do something else if the variable is set with a value. That’s perfectly fine as long as you know how to use quotes to avoid these kinds of parsing problems.

To make this a bit more realistic, let’s make quote_problem4.sh so that it will accept a user-defined value:

#!/bin/bash
number=$1
if [ $number = 1 ]; then
echo "Number equals 1"
<!-- page: 570 (printed 573) -->
else
echo "Number does not equal 1"
fi

Let’s see how it works with different values:

Terminal window
donnie@fedora:~$ ./quote_problem4.sh 1
Number equals 1
donnie@fedora:~$ ./quote_problem4.sh 5
Number does not equal 1
donnie@fedora:~$ ./quote_problem4.sh
./quote_problem4.sh: line 4: [: =: unary operator expected
Number does not equal 1
donnie@fedora:~$

It works fine with either 1 or 5 as a value, but doesn’t work when I don’t supply a value. So, it appears that I forgot to quote the $number. Not to worry, I’ll fix that in quote_problem5.sh:

#!/bin/bash
number=$1
if [ "$number" = 1 ]; then
echo "Number equals 1"
else
echo "Number does not equal 1"
fi

Let’s see what we have now:

Terminal window
donnie@fedora:~$ ./quote_problem5.sh 1
Number equals 1
donnie@fedora:~$ ./quote_problem5.sh 5
Number does not equal 1
donnie@fedora:~$ ./quote_problem5.sh
Number does not equal 1
donnie@fedora:~$

It works like a champ, which means that once again, we’ve achieved coolness.

Since we’ve been working with tests, let’s see what happens when we leave out a space, as I did in space_problem1.sh:

#!/bin/bash
number=$1
if [ "$number" = 1 ]; then
echo "Number equals 1"
else
echo "Number does not equal 1"
fi

It’s the same as the quote_problem5.sh script, except that I deleted the space between the [ and the $number”. Here’s what happens when I run it:

Terminal window
donnie@fedora:~$ ./space_problem1.sh
./space_problem1.sh: line 4: [: =: unary operator expected
Number does not equal 1
donnie@fedora:~$

Amazingly enough, it gives me the exact same error message as when I forgot to quote my $number variable. So, this shows us two things. First, you need to be careful about placing spaces in your test conditions. Secondly, you can’t always depend upon the shell’s error message to tell you exactly what the problem is. In this case, the exact same message showed up for two completely different errors.

But wait! Here’s one more way to troubleshoot this problem. We’ll just use the -u shell option to check for uninitialized variables, as you see here in the quote_problem6.sh script:

#!/bin/bash -u
number=$1
if [ $number = 1 ]; then
echo "Number equals 1"
else
echo "Number does not equal 1"
fi

The only difference between this script and the previous one is that I added -u to the end of the she-bang line. Let’s see what happens when I run it without supplying a value for $1:

Terminal window
donnie@fedora:~$ ./quote_problem6.sh
./quote_problem6.sh: line 3: $1: unbound variable
donnie@fedora:~$

This is cool, because it tells us exactly what the problem is, instead of just showing us a generic error message. If you need to see a more verbose message, just add the v option, like this:

#!/bin/bash -uv

Running the script now looks like this:

donnie@fedora:~$ ./quote_problem6.sh
#!/bin/bash -uv
number=$1
<!-- page: 572 (printed 575) -->
./quote_problem6.sh: line 3: $1: unbound variable
donnie@fedora:~$

When you’re finished debugging, be sure to delete the -u or -uv That’s because it could cause problems in production scripts.

I’ll show you more about using the -u option in just a few pages, in the Using Shell Script Debugging Tools section.

For the next problem, you’ll need to buckle your seat belt. That’s because things are going to get wild.

Creating a Wild Loop

When you create some sort of loop, it’s real easy to accidentally create one that will run forever until you stop it. For example, let’s look at the wild_loop1.sh script:

#!/bin/bash
# while loop running wild
count=30
limit=25
while [ "$count" -gt "$limit" ];
do
echo $count
(( count = (count + 1)))
done

This loop begins with a count value of 30, which will increment by 1 on each iteration of the loop. It’s supposed to go until count reaches a value of 25. Okay, I know that the problem is blatantly obvious this time, but bear with me anyway. This could happen if a coder got in a hurry and just didn’t notice it. Anyway, trying to run this will output a list of numbers that just keeps on going and going. No matter how fast you hit Ctrl-c, the output will scroll past the top of your terminal, so that you’ll never get to see the top part of the output. So, I’ll fix that by directing the output into a text file. First though, I’ll open a second terminal window, and create a blank text file, like this:

Terminal window
donnie@fedora:~$ touch wild_loop.txt
donnie@fedora:~$

Next, while still in that window, I’ll open the file with tail -f, in order to see the file as it gets updated:

Terminal window
donnie@fedora:~$ tail -f wild_loop.txt

I’ll now go back to my first terminal window, and run the wild_loop1.sh script, like this:

Terminal window
donnie@fedora:~$ ./wild_loop1.sh > wild_loop.txt

I hit Ctrl-c after only a few seconds. But, as you see in the second window, the count really went wild:

Open the wild_loop.txt file in less, and you’ll see that the script really does have the output begin at 30.

As I said before, the problem here is obvious. It’s just that I accidentally reversed the values of count and limit. So, let’s fix that in wild_loop2.sh:

#!/bin/bash
# while loop fixed
count=25
limit=30
while [ "$count" -lt "$limit" ];
do
echo $count
(( count = (count + 1)))
done

This time, count is set to 25 and limit is set to 30. Running this script should work better. Let’s see:

Terminal window
donnie@fedora:~$ ./wild_loop2.sh
25
26
27
28
29
donnie@fedora:~$

Oh yeah, that looks much better.

There are a whole lot more shell scripting pitfalls that I could share with you. But, in the interest of not trying to reinvent the proverbial wheel, I’ll end this here and instead share a few excellent resources that you might find useful.

File names and Pathnames in Shell: How to do it Correctly: https://dwheeler.com/essays/filenames-in-shell.html

Common Shell Script Mistakes: https://www.pixelbeat.org/programming/shell_script_mistakes.html

Bash Pitfalls: http://mywiki.wooledge.org/BashPitfalls

All right, let’s move on to the debugging tools.

Using Shell Script Debugging Tools and Techniques

There are a few different debugging tools that we can use, which include shellcheck, checkbashisms, and shall. We’ve already looked at them in Chapter 19—Shell Script Portability, so we won’t look at them again here. Instead, I’ll present some tools and techniques that we haven’t covered yet.

Using echo Statements

Sometimes, if you have a problem with a shell script that you can’t figure out, placing echo statements in strategic locations can help you find the problem.

You may see in other references that some people think of echo statements as the poor man’s debugging tool. That’s because echo is always available, and can be used if you can’t use anything else.

Back in Chapter 16, Creating User Interfaces with yad, dialog, and xdialog, I showed you the xdialog-1lo2.sh script, which can automatically detect two things.

It can detect whether or not the Xdialog utility is present.

It can also detect if your machine has a desktop environment installed.

If both a desktop environment and the Xdialog utility are detected, the script will run the graphical Xdialog utility. Otherwise, the script will run the ncurses-based dialog utility. Here’s what the script looks like:

#!/bin/bash
command -v Xdialog
if [[ $? == 0 ]] && [[ -n $DISPLAY ]]; then
diag=Xdialog
else
diag=dialog
fi
$diag --title "Dialog message box" \
--begin 2 2 \
--msgbox "\nHowdy folks!" 15 50
clear

As a reminder, the DISPLAY environmental variable will have a non-zero length assigned value if a desktop environment is installed, and won’t have an assigned value if no desktop environment is installed. The -n in the [[ -n DISPLAY]]statementtestsforthepresenceofanon−zerolengthassignedvalue.(The−nactuallystandsfornon−zero.)So,ifthe[[−nDISPLAY ]] statement tests for the presence of a non-zero length assigned value. (The -n actually stands for non-zero.) So, if the [[ -n DISPLAY ]] test returns a value of 0, which means that the condition is true, then a desktop environment has been detected.

Originally though, the script looked like this, as you see in the xdialog-hello2-broken.sh script:

#!/bin/bash
command -v Xdialog
if [[ -n $DISPLAY ]] && [[ $? == 0 ]]; then
diag=Xdialog
else
diag=dialog
fi
$diag --title "Dialog message box" \

As you see, the only difference is that the test conditions in the two scripts are in a different order. The script that works has the [[ ?==0]]testfirst,andthebrokenscripthasthe[[−n? == 0 ]] test first, and the broken script has the [[ -n DISPLAY ]] condition first.

When I tried running the original script, which had [[ -n $DISPLAY ]] first, it just wouldn’t work. I mean, it would work fine on desktop machines that had Xdialog installed or machines that were running in text mode. But, on desktop machines that didn’t have Xdialog installed, it would always tell me that it is installed. And of course, running the script would always fail because it was trying to run Xdialog. I couldn’t understand the reason for this, so I had to do some troubleshooting.

I’ve never installed Xdialog on my Fedora workstation, so I can use it to show you my troubleshooting steps. When you try this demo, be sure to try it on a desktop-type virtual machine that also does not have Xdialog installed.

You can start troubleshooting by placing an echo $? command and a sleep 10 command just under the command -v Xdialog line. The script now looks like this:

#!/bin/bash
command -v Xdialog
echo $?
sleep 10
if [[ -n $DISPLAY ]] && [[ $? == 0 ]]; then
diag=Xdialog
else
diag=dialog
fi
$diag --title "Dialog message box" \
--begin 2 2 \
--msgbox "\nHowdy folks!" 15 50
clear

I wanted to see if the exit code would be 0 or 1, and the sleep 10 command would pause the script long enough so that I could see the echo $? output.

I inserted the sleep 10 command to give myself ten seconds to see the output of the echo $? command. Otherwise, the clear command at the end would clear away the output before I could see it. If you prefer, you can omit the sleep 10 command, and instead just comment out the clear command. Either way works, so the choice is yours.

A 1 would mean that Xdialog is not installed, and a 0 would mean that it is installed. Placing the echo and sleep commands under the command -v Xdialog command would show me if the script was properly detecting if the package was installed. Running the script now looks like this:

Terminal window
donnie@fedora:~$ ./xdialog-hello2-broken.sh
1

The 1 exit code means that the script properly detects that Xdialog is not present. So, that portion of the script works. Next, you can comment out the whole if . then. .else stanza, and place an [[ -n DISPLAY ]] && echo ? statement and a sleep 10 statement just above it, like this:

#!/bin/bash
command -v Xdialog
[[ -n $DISPLAY ]] && echo $?
sleep 10
#if [[ -n $DISPLAY ]] && [[ $? == 0 ]]; then
# diag=Xdialog
#else
# diag=dialog
#fi
$diag --title "Dialog message box" \
--begin 2 2 \
--msgbox "\nHowdy folks!" 15 50
clear

Running the script with this modification looks like this:

Terminal window
donnie@fedora:~$ ./xdialog-hello2-broken.sh
0

The 0 exit code indicates a true condition, which means that a desktop environment is indeed installed. So, that part of the code also works properly.

At this point we need to start thinking logically. If the [[ -n DISPLAY]]returnsa0exitcode,howwouldthataffectthe[[DISPLAY ]] returns a 0 exit code, how would that affect the [[ ? == 0 ]] part? Well, it turns out that the ?inthesecondtestconditionwaslookingatthe0exitcodethatwasreturnedbythefirsttestcondition,insteadoftheexitcodefromthecommand−vXdialogcommand.Soonadesktopmachine,the? in the second test condition was looking at the 0 exit code that was returned by the first test condition, instead of the exit code from the command -v Xdialog command. So on a desktop machine, the ? would always be looking at a 0 exit code, whether or not Xdialog was present. Fixing that was just a simple matter of swapping the order of the two test conditions, as you see above in the xdialog-hello2.sh script.

In hindsight, the solution to this problem should have been obvious. But for some reason I was having a mental block that prevented me from seeing that. It just goes to show that even the best of us can sometimes be buffaloes by simple scripting errors.

All right, let’s move on to the next debugging tool.

Using xtrace with your problematic scripts shows the actual execution of the commands in the scripts, along with their output. This can help you track down the source of your problems.

You can use xtrace mode in three different ways, which are:

  • Append -x to the shebang line. This works for all shells that we’ve been working with. For example, if you’re writing a bash script, then the shebang line will be #!/bin/bash -x. If you’re creating a script where portability matters, you can use #!/bin/sh -x.
  • Place a set -x command into the script where you want to turn on debugging mode.
  • Run the set -x command from the command-line before you invoke a script.

To demo this, let’s look at the xdialog-hello2-broken2.sh script, which has the same problem as the xdialog-hello2-broken.sh script that you saw in the previous section..

#!/bin/bash -x
command -v Xdialog
if [[ -n $DISPLAY ]] && [[ $? == 0 ]]; then
diag=Xdialog
sleep 10
else
diag=dialog
sleep 10
fi
$diag --title "Dialog message box" \
--begin 2 2 \
--msgbox "\nHowdy folks!" 15 50
clear

Here, I placed a -x at the end of the shebang line, and then placed a sleep 10 line after the diag=Xdialog line and the diag=dialog line. Now, let’s run it.

Terminal window
donnie@fedora:~$ ./xdialog-hello2-broken2.sh
+ command -v Xdialog
+ [[ -n :0 ]]
+ [[ 0 == 0 ]]
+ diag=Xdialog
+ sleep 10

You can immediately see how this is even more useful than using echo commands. The [[ -n :0 ]] line is the expansion of the [[ -n $DISPLAY ]] test. It shows that the DISPLAY variable does indeed have an assigned value (:0), which means that a desktop environment is installed. But, the real key here is the [[ 0 == 0 ]] line, which is the expansion of the [[ $? == 0 ]] test. Invoking Xdialog from this script requires that $? equals 0, which would require that both of our test conditions return a 0.

This in turn requires that both xdialog and a desktop environment are present. But, even though xdialog is not installed on this machine, this script erroneously shows that it is, as you see in the diag=xdialog line. So again, the only obvious answer is to swap the test conditions, as we did before, and test it again. After you do that, the [[ $? == 0 ]] will expand to [[ 1 == 0 ]], which is what we want to see in this case.

If you’re using#!/usr/bin/env bash as your shebang line, than appending -x to the end of the shebang line won’t work. That’s because env only recognizes one option at a time, which in this case is bash. So instead, you’ll need to either use set -x from the command-line before you run the script, or place a set -x command inside the script, like this:

#!/usr/bin/env bash
set -x
...
...

If you use set -x on the command-line, you can turn debug mode back off by doing set +x.

If -x alone doesn’t show you enough information, you can enable verbose mode by adding the v option, as you see in xdialog-hello2-broken4.sh:

#!/bin/bash -xv
command -v Xdialog
if [[ -n $DISPLAY ]] && [[ $? == 0 ]]; then
diag=Xdialog
sleep 10
else
diag=dialog
sleep 10
fi
$diag --title "Dialog message box" \
--begin 2 2 \
--msgbox "\nHowdy folks!" 15 50
clear

Here’s the output:

donnie@fedora:~$ ./xdialog-hello2-broken4.sh
#!/bin/bash -xv
command -v Xdialog
<!-- page: 580 (printed 583) -->
+ command -v Xdialog
if [[ -n $DISPLAY ]] && [[ $? == 0 ]]; then
diag=Xdialog
sleep 10
else
diag=dialog
sleep 10
fi
+ [[ -n :0 ]]
+ [[ 0 == 0 ]]
+ diag=Xdialog
+ sleep 10

In addition to what we saw before, we now see the entire script echoed back at us. We also see that the value of the diag variable is Xdialog. Since Xdialog isn’t installed on this machine, the diag value should be dialog.

If you need a permanent record of your debugging for further study, you can redirect the -x output into a text file. The -x output is considered as stderr output, so you’ll redirect it like so:

Terminal window
donnie@fedora:~$ ./xdialog-hello2-broken4.sh 2> debug.txt

When you’re through debugging, be sure to remove the -x or set -x options from your script before you put it into production.

Okay, let’s move on to our next trick.

As I said at the beginning of this chapter, in the Understanding Common Scripting Errors section, it’s sometimes desirable to define a variable in a script without assigning an initial value to it. But, sometimes it isn’t. You can track down uninitialized variables by appending a -u to the end of your shebang line. In bash for example, you can use #!/bin/bash -u, which will turn this feature on for the entire script. Or, you can place a set -u command any place in the script where you’d like to start checking. For example, let’s look at the unassigned_var1.sh script, which has variable checking turned off:

#!/bin/bash
echo "The uninitialized myvar, without setting -u, looks like this : " $myvar
echo
myvar=Donnie
echo "I've just initialized myvar."
echo "The value of myvar is: " $myvar

Here’s the output:

Terminal window
donnie@fedora:~$ ./unassigned_var1.sh
The uninitialized myvar, without setting -u, looks like this :
I've just initialized myvar.
The value of myvar is: Donnie
donnie@fedora:~$

As you see, without the -u setting, the script runs to completion. It’s just that trying to echo the value of the uninitialized myvar just shows us a blank space. Next, let’s turn on variable checking by adding the -u option, as you see in the unassigned_var2.sh script:

#!/bin/bash -u
echo "The uninitialized myvar, without setting -u, looks like this : " $myvar
echo
myvar=Donnie
echo "I've just initialized myvar."
echo "The value of myvar is: " $myvar

Let’s see what this does:

Terminal window
donnie@fedora:~$ ./unassigned_var2.sh
./unassigned_var2.sh: line 2: myvar: unbound variable
donnie@fedora:~$

This time the script failed as soon as it saw the uninitialized variable.

You can set the -u option anywhere in the script you like, by using set -u, as you see here in the unassigned_var3.sh script:

#!/bin/bash
echo "The uninitialized myvar, without setting -u, looks like this : " $myvar
echo
echo "I'm now setting -u."
set -u
myvar=Donnie
echo "I've just initialized myvar."
echo "The value of myvar is: " $myvar
echo
echo "Let's now try another uninitialized variable."
echo "Here's the uninitialized " $myvar2

So now, I have one uninitialized variable at the top, on line 2. (Let’s just say that for whatever reason, I want this particular variable to be uninitialized.) I then turn on variable checking on line 5. Let’s see how this runs:

Terminal window
donnie@fedora:~$ ./unassigned_var3.sh
<!-- page: 582 (printed 585) -->
The uninitialized myvar, without setting -u, looks like this :
I'm now setting -u.
I've just initialized myvar.
The value of myvar is: Donnie
Let's now try another uninitialized variable.
./unassigned_var3.sh: line 11: myvar2: unbound variable
donnie@fedora:~$

Before I turn on variable checking, the uninitialized myvar just shows us a blank space. After I turn on variable checking, I initialized myvar with a value of Donnie, and it prints out normally. But, the uninitialized myvar2 at the end crashes the script.

If you search the web for shell scripting security tutorials, you’ll find several that tell you to make either -u or set -u a permanent part of your scripts. The authors of these tutorials say that it enhances the security of your scripts, without giving any convincing explanation of why or how. Using -u or set -u is great for debugging, but it should only be used for just that—debugging! So, when you’re through debugging your scripts, be sure to remove the -u or the set -u before you place the script into production. Otherwise, your scripts could give you some rather unpredictable results.

Also, be aware that using -u can also help you detect typos in your scripts. For example, if you define a variable as mynum=1, but accidentally call back the value with $mymum, the -u will detect that mymum is an unset variable.

That about does it for the discussion of uninitialized variables. Let’s move on to our next trick.

Checking for Errors with the -e Option

Our next trick is to use either the -e shell option or the set -e command to test our scripts for errors that cause commands within the script to fail. Let’s look at the bad_dir1.sh script to see how that works.

#!/bin/bash
mkdir mydir
cd mydire
ls

With this, I want to create the mydir directory, cd into it, and then do a file listing. But, my typing isn’t up to what it should be today, so in the cd line I accidentally typed mydire, instead of mydir. Let’s see what happens when I run it.

Terminal window
donnie@fedora:~$ ./bad_dir1.sh
./bad_dir1.sh: line 4: cd: mydire: No such file or directory
15827.zip.zip
18.csv
2023-08-01_15-23-31.mp4

Yeah, this problem is obvious, but that’s okay. That’s because the -e option does more than just identify the problem. It would cause the script to immediately exit if any command fails. Let’s put this option into the bad_dir2.sh script to see how that works.

#!/bin/bash -e
mkdir mydir
cd mydire
ls

All I did here was to insert the -e option. Now, I’ll delete the mydir directory that the first script created, and try running this one.

Terminal window
donnie@fedora:~$ rm -rf mydir
donnie@fedora:~$ ./bad_dir2.sh
./bad_dir2.sh: line 4: cd: mydire: No such file or directory
donnie@fedora:~$

Using -e also works when the failing command is part of a compound command structure, as you see in bad_dir3.sh.

#!/bin/bash -e
mkdir mydir && cd mydire
ls

As before, I’ll delete the mydir directory that the previous script created, and then run bad_dir3.sh, which looks like this:

Terminal window
donnie@fedora:~$ ./bad_dir3.sh
./bad_dir3.sh: line 3: cd: mydire: No such file or directory
donnie@fedora:~$

So again, the -e stopped this script in its tracks when the cd command failed.

I know what you’re thinking, and I know that that’s a bit creepy. You’re thinking that the kinds of errors that -e would detect are fairly obvious. That’s because with these types of errors, the shell will display an error message that pinpoints the problem. So then, why do we need -e? Well, think of -e and set -e as more of a safety mechanism than a debugging tool. For example, if the next command after trying to cd into a non-existent directory is to rm all files, then allowing the script to run after the cd command fails could be disastrous.

Okay, I’ve told you the good stuff about -e and set -e. Now, let me tell you some not-so-good stuff.

Understanding the Problems with set -e and -e

Although -e and set -e can be helpful, they can also cause you headaches. Sometimes, they can actually break a script that worked before. Here’s what I mean.

The set -e and -e settings work by detecting if a command in the script returns an exit code of something other than 0.

Remember that an exit code of 0 indicates a successful command execution, and a non-0 exit code indicates a failure.

Sometimes though, you’ll need for some commands in your script to return a non-0 exit code in order for the script to work. This makes the operation of set -e and -e unpredictable, at best. For example, take a look at this set_e_fails1.sh script:

#!/bin/bash
set -e
i=0
let i++
echo "i is $i"

Note that let i++ is a bashism that I haven’t yet shown you. You can replace it with i=$(( i + 1 )) in order to make the script portable to non-bash shells.

This creates the i variable with a value of 0, increments that value by 1, and then prints out the final value of i. But, watch what happens with the -e setting:

Terminal window
donnie@fedora:~$ ./set_e_fails1.sh
donnie@fedora:~$

Well, it prints out nothing. Let’s see what happens if I comment out the set -e command, like so:

#!/bin/bash
# set -e
i=0
let i++
echo "i is $i"

Let’s run it again.

Terminal window
donnie@fedora:~$ ./set_e_fails1.sh
<!-- page: 585 (printed 588) -->
i is 1
donnie@fedora:~$

So, the script runs perfectly fine without the set -e, but inserting the set -e breaks it. I know, that’s crazy, right? To help us figure out what’s going on, let’s create the set_e_fails2.sh script, like so:

#!/bin/bash
i=0
echo "Exit code after setting the value of i: " $?
let i++
echo "Exit code after incrementing i: " $?
echo "i is $i"
echo "Exit code after displaying new value of i: " $?

The only difference is that I omitted the set -e line, and inserted echo statements that display the exit code of each command. Now, to run it:

Terminal window
donnie@fedora:~$ ./set_e_fails2.sh
Exit code after setting the value of i: 0
Exit code after incrementing i: 1
i is 1
Exit code after displaying new value of i: 0
donnie@fedora:~$

The Exit code after incrementing i: 1 line shows us the problem. It’s just that for some truly bizarre reason that I don’t understand, the let i++ command produces an exit code of 1, even though the command is successful. So in this case, using -e created a problem, instead of solving one. (Curiously though, using the portable i=$(( i + 1 )) construct will return exit code 0, which will prevent this problem. I have no idea why that is.)

I mentioned in the Checking for Undefined Variables section that some articles you’ll find on the web recommend making either -u or set -u a permanent part of your scripts, in order to enhance security. These authors actually recommend making both the -e/set -e and -u/set -u a permanent part of your scripts. But, as I’ve just demonstrated, -e/set -e can be rather unpredictable, and could cause you more problems than it solves. At any rate, if you do use this tool for troubleshooting, be sure to delete it from your scripts before you place them into production.

Although my personal belief is that -e and set -e can be useful when used with caution, that’s actually a controversial opinion. In the following article, you’ll see a lengthy write-up about why you should never, ever use -e or set -e:

BashFAQ105—Greg’s Wiki:

https://mywiki.wooledge.org/BashFAQ/105

This author’s belief is that you would be better served by creating your own error checks, rather than relying on -e/set -e.

If you like, give the page a visit, and work through the examples that the author provides. The author also provides a link to a page with the counter-argument to this, so be sure to check that out as well so that you can decide for yourself.

Okay, let’s move on to our final debugging tool.

Using bash Debugger

The bash Debugger, which you’ll normally see referred to as bashdb, allows you to step through a bash script, one command at a time. This allows you to see what each command in the script is doing before moving on to the next command. It’s pretty simple to use, once you get installed.

You’ll find a lot of bashdb tutorials on the web, but a lot of them are very old, and show you an obsolete method for installing bashdb. That’s because years ago, bashdb was included in the repositories of pretty much every Linux distro. So, you could install it with your normal package manager as those tutorials showed.

Unfortunately, for some strange reason, bashdb has been removed from most, if not all, Linux repositories. So now, if you want to run bashdb on Linux, you’ll need to compile it from source code as I’m about to show you.

On the other hand, bashdb is in the FreeBSD repository and in the Homebrew repository for macOS, so you’re all good there.

iv. let’s look at installing bashdb.

Installing bashdb on Linux

I mentioned above in the info box, you’ll need to install bashdb from source code. Don’t fret though, because it’s easy.

  1. You’ll first need to install the autoconf and texinfo packages from your normal distro repository, using your distro’s normal package manager.

  2. Download the bashdb source code by doing:

git clone https://github.com/rocky/bashdb.git

  1. cd into the bashdb/ directory that the git command created.

  2. Run the following set of commands to compile and install bashdb:

./autogen.sh ./configure make && make check sudo make install

That’s all there is to it.

Installing bashdb on FreeBSD

This is even easier. Just do:

sudo pkg install bashdb

Installing on macOS

On a Mac with Homebrew installed, just do:

brew install bashdb

Now that bashdb is installed, let’s see if we can actually use it.

Let’s start with a clean, unmodified copy of the original broken xdialog script, which I’ll call xdialog-hello2-broken5.sh, which looks like this:

#!/bin/bash
command -v Xdialog
if [[ -n $DISPLAY ]] && [[ $? == 0 ]]; then
diag=Xdialog
else
diag=dialog
fi
$diag --title "Dialog message box" \
--begin 2 2 \
--msgbox "\nHowdy folks!" 15 50
clear

As you’ve seen in the Using xtrace for Debugging section, the problem is that the script won’t properly detect if both Xdialog and a desktop display are installed. Let’s step through this with bashdb to see what it can tell us. Begin like so:

Terminal window
donnie@fedora:~$ bashdb ./xdialog-hello2-broken5.sh
bash debugger, bashdb, release 5.2-1.1.2
Copyright 2002-2004, 2006-2012, 2014, 2016-2019, 2021, 2023 Rocky Bernstein
This is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
(/home/donnie/xdialog-hello2-broken5.sh:3):
3: command -v Xdialog
bashdb<0>

This runs the first command in the script, and then dumps us out at the bashdb command prompt. To run the next command, just enter step, like so:

Terminal window
...
...
bashdb<0> step
(/home/donnie/xdialog-hello2-broken5.sh:4):
4: if [[ -n $DISPLAY ]] && [[ $? == 0 ]]; then
bashdb<1>

Here, we see the DISPLAY variable that’s inside the test construct. Let’s examine that variable to see what its value is, by using the examine command:

Terminal window
bashdb<1> examine DISPLAY
declare -x DISPLAY=":0"
bashdb<2>

The declare -x part means that bashdb is marking the DISPLAY variable for export to subsequent commands. But, that’s not the important part. What’s important is that the DISPLAY variable has a value of 4, which means that the [[ -n $DISPLAY ]] test will return a value of 0 to indicate a true condition.

Instead of using the examine DISPLAY command, you can use the print $DISPLAY command, like so:

Terminal window
bashdb<1> print $DISPLAY
:0
bashdb<2>

This way, the only thing that shows up is just the actual DISPLAY value.

At this point, we need to put on our thinking caps and ponder what it means to have this DISPLAY test come before the ?test.Well,we′vealreadycomeupwiththatanswerwhenweusedtheechostatementandxtracemethodstotroubleshootthis.It′sjustthatifwedotheDISPLAYdetectionfirst,the? test. Well, we've already come up with that answer when we used the echo statement and xtrace methods to troubleshoot this. It's just that if we do the DISPLAY detection first, the ? value in the second test will always be 0, even if no Xdialog executable is detected. But, for the sake of showing you a bit more, let’s say that we haven’t figured that out, and need to see more of what the script is doing. To do that, enter the series of commands that you see in the next snippet:

Terminal window
bashdb<2> step
(/home/donnie/xdialog-hello2-broken5.sh:4):
4: if [[ -n $DISPLAY ]] && [[ $? == 0 ]]; then
[[ $? == 0 ]]
bashdb<3> step
(/home/donnie/xdialog-hello2-broken5.sh:5):
5: diag=Xdialog
bashdb<4> print $diag
bashdb<5> step
(/home/donnie/xdialog-hello2-broken5.sh:10):
10: $diag --title "Dialog message box" \
bashdb<6> print $diag
Xdialog
bashdb<7>

I started this by issuing two step commands, which gets me down to where the diag variable is defined and what its assigned value is. I then issued the print diagcommand,butnothingshowedup.Then,Iissuedanotherstepcommand,followedbyanotherprintdiag command, but nothing showed up. Then, I issued another step command, followed by another print diag command. At that point, I finally see that the diag variable has the value of Xdialog, even though Xdialog isn’t installed on this workstation.

The clear advantage of using bashdb is that I didn’t have to modify the script in order to debug it. As you see, I didn’t have to add any echo statements to obtain the value of the DISPLAY and diag variables. I also didn’t have to add a sleep command or comment out the ending clear command in order to prevent the screen from clearing before I could see the DISPLAY value. Obviously, this is a big win for bashdb.

Of course, you might at times need to find extra information about what you can do with bashdb. Let’s look at that next.

When you install bashdb, a man page will get installed with it. Frankly though, it doesn’t tell you much. Fortunately, bashdb has a built-in help function that you can use any time that you’re at the bashdb command-prompt. Just enter the help command, and you’ll see this:

bashdb<0> help
Available commands:
------------------
action complete display export history print search source undisplay
alias condition down file info pwd set step untrace
backtrace continue edit finish kill quit shell tbreak up
break debug enable frame list return show trace watch
clear delete eval handle load reverse signal tty watche
commands disable examine help next run skip unalias
Readline command line editing (emacs/vi mode) is available.
Type "help" followed by command name for full documentation.
bashdb<1>

This shows the list of available bashdb commands. To see how to use a particular command, just enter help followed by the command name, like so:

bashdb<1> help break
**break** [*loc-spec*]
Set a breakpoint at *loc-spec*.
If no location specification is given, the current line will be used.
Multiple breakpoints at one place are permitted, and useful if conditional.
For *loc-spec* paths with space characters please use octal escape, e.g.:
break /some/path\040with\040spaces/script.sh:3
See also:
----------
"tbreak" and "continue"
Aliases for break: b
bashdb<2>

Figure 21.3: Getting help for the break command

That about wraps things up for this chapter. Let’s summarize and move on.

In this chapter, we covered some cool tips and tricks that can help you troubleshoot your code. We began by looking at some common shell scripting errors, and showed how to find them in a broken script. We then looked at some common debugging tools and techniques. For the -u and -e shell options, I showed you both the pros and the cons of using them. Finally, I showed you how to install and use bashdb.

In the next chapter, we’ll take a brief look at scripting with zsh. I’ll see you there.

This time, instead of presenting you with questions to answer, I’ll present you with some buggy shell scripts. Try running them to observe the errors, and then try to debug them. Can you debug them? Sure you can. I have faith in you.

  1. We’ll start with the bug1.sh script:
#!/bin/bash
echo "Fix this script...I've got bugs"
a=45
if [$a -gt 27 ]
then
  1. Here’s the bug2.sh script:
#!/bin/bash
echo "Fix this script...I've got bugs"
for i in 1 2 3 4 5 6 7 8 9
do
echo $i
exit
  1. Now, for bug3.sh:
#!/bin/bash
echo "Fix this script...I've got bugs"
scripts=$(ls | grep [a-z]*.sh)
echo $scripts
exit
  1. Here’s the fourth and final, bug4.sh:
#!/bin/bash
echo '1 2 3' > sample.data
cut -d' ' -f1,3 sample.data | read x z
echo $((x+z))

Further Reading

Debugging your shell scripts with bashdb: https://www.linux.com/news/debug-your-shell-scripts-bashdb/ Debugging bash scripts with the bashdb debugger: https://dafoster.net/articles/2023/02/22/debugging-bash-scripts-with-the-bashdb-debugger/

Answers

  1. In the if statement, you need to insert a blank space between the [ and the $a.
  2. You need to place a done statement after the echo $i statement.
  3. There are a couple of problems with this script. First, the regular expression is set up wrong, which causes you to get either no or incorrect output from this script. Instead of [a-z]*.sh, it should be [a-z].sh. (The * actually isn’t needed for this.)

You can review the concept of regular expressions in Chapter 9—Filtering Text with grep, sed, and Regular Expressions.

There’s also the fact this regular expression isn’t doing much for us. Unless you have scripts with filenames that consist of nothing but either digits or upper-case characters, this grep command is going to show you all of the scripts in your directory. So, you could probably just omit the grep command altogether, and go with a simple ls *.sh command.

Finally, in the echo statement, you need to surround the variable with a pair of double quotes, like this:

echo "$scripts"

This will prevent problems with filenames that have blank spaces in them.

  1. This script is supposed to take values from the first and third field of the sample.data file that the script created, and add them together. The values of the first and third fields are 1 and 3, so the sum of the two should be 4. However, here’s how it looks when you run it:
Terminal window
donnie@fedora:~$ ./bug4.sh
0
donnie@fedora:~$

The problem is that the cut command on line 3 is piping its output into the read command. The problem with that is that the read command is built into the shell, instead of having its own executable file.

That’s significant, because you can only pipe output of one command into a command that has its own executable. So, you can’t pipe output into a command that’s a shell builtin.

Instead of using a pipe, you can instead send the first and third field values to the tmp.data file, and then use the input redirector to obtain the input from the tmp.data file, as you see here in the bug5.sh script:

#!/bin/bash
echo '1 2 3' > sample.data
cut -d' ' -f1,3 sample.data > tmp.data
read x z < tmp.data
echo $((x+z))

Another option would be to use a here document, as you see in the bug6.sh script:

#!/bin/bash
echo '1 2 3' > sample.data
read -r x z <<<$(cut -d' ' -f1,3 sample.data)
echo $((x+z))

Either way, you’ll now see the correct results:

Terminal window
donnie@fedora:~$ ./bug5.sh
4
donnie@fedora:~$ ./bug6.sh
4
donnie@fedora:~$

Join our community on Discord!

Read this book alongside other users, Linux experts, and the author himself.

Ask questions, provide solutions to other readers, chat with the author via Ask Me Anything sessions, and much more. Scan the QR code or visit the link to join the community.

https://packt.link/SecNet