Debugging Shell Scripts
local graph
Chapter 21 — Debugging Shell Scripts
Section titled “Chapter 21 — Debugging Shell Scripts”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.gitUnderstanding Common Scripting Errors
Section titled “Understanding Common Scripting Errors”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.
Not Enough Quoting
Section titled “Not Enough Quoting”You can have a few different problems if you don’t surround variable names with quotes. Here are some examples.
Filenames with Blank Spaces
Section titled “Filenames with Blank Spaces”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:
donnie@fedora:~/quoting_demo$ touch somefile_$(date).txtdonnie@fedora:~/quoting_demo$Okay, let’s look at the file:
donnie@fedora:~/quoting_demo$ ls -ltotal 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_Tuedonnie@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:
donnie@fedora:~/quoting_demo$ dateTue Aug 20 03:13:23 PM EDT 2024donnie@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:
donnie@fedora:~/quoting_demo$ touch somefile_"$(date)".txtdonnie@fedora:~/quoting_demo$ ls -ltotal 0-rw-r--r--. 1 donnie donnie 0 Aug 20 15:15 'somefile_Tue Aug 20 03:15:37 PM EDT2024.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/bashnumber=1if [ $number = 1 ]; then echo "Number equals 1"else echo "Number does not equal 1"fiAll it does is to tell us whether or not the value of number is 1. Running the script looks like this:
donnie@fedora:~$ ./quote_problem1.shNumber equals 1donnie@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:
donnie@fedora:~$ ./quote_problem1.shNumber does not equal 1donnie@fedora:~$Now, let’s try that with an unset variable, as you see in quote_problem2.sh:
#!/bin/bashnumber=if [ $number = 1 ]; then echo "Number equals 1"else echo "Number does not equal 1"fiWhen 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.
donnie@fedora:~$ ./quote_problem2.sh./quote_problem2.sh: line 4: [: =: unary operator expectedNumber does not equal 1donnie@fedora:~$The problem is that the if [ number that’s in the test statement with a pair of double quotes, as you see in quote_problem3.sh:
#!/bin/bashnumber=if [ "$number" = 1 ]; then echo "Number equals 1"else echo "Number does not equal 1"fiRunning this script will show the correct results:
donnie@fedora:~$ ./quote_problem3.shNumber does not equal 1donnie@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/bashnumber=$1if [ $number = 1 ]; then echo "Number equals 1"
<!-- page: 570 (printed 573) -->
else echo "Number does not equal 1"fiLet’s see how it works with different values:
donnie@fedora:~$ ./quote_problem4.sh 1Number equals 1donnie@fedora:~$ ./quote_problem4.sh 5Number does not equal 1donnie@fedora:~$ ./quote_problem4.sh./quote_problem4.sh: line 4: [: =: unary operator expectedNumber does not equal 1donnie@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/bashnumber=$1if [ "$number" = 1 ]; then echo "Number equals 1"else echo "Number does not equal 1"fiLet’s see what we have now:
donnie@fedora:~$ ./quote_problem5.sh 1Number equals 1donnie@fedora:~$ ./quote_problem5.sh 5Number does not equal 1donnie@fedora:~$ ./quote_problem5.shNumber does not equal 1donnie@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/bashnumber=$1if [ "$number" = 1 ]; then echo "Number equals 1"elseecho "Number does not equal 1"fiIt’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:
donnie@fedora:~$ ./space_problem1.sh./space_problem1.sh: line 4: [: =: unary operator expectedNumber does not equal 1donnie@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 -unumber=$1if [ $number = 1 ]; then echo "Number equals 1"else echo "Number does not equal 1"fiThe 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:
donnie@fedora:~$ ./quote_problem6.sh./quote_problem6.sh: line 3: $1: unbound variabledonnie@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 -uvRunning the script now looks like this:
donnie@fedora:~$ ./quote_problem6.sh#!/bin/bash -uvnumber=$1<!-- page: 572 (printed 575) -->./quote_problem6.sh: line 3: $1: unbound variabledonnie@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 wildcount=30limit=25while [ "$count" -gt "$limit" ];do echo $count (( count = (count + 1)))doneThis 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:
donnie@fedora:~$ touch wild_loop.txtdonnie@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:
donnie@fedora:~$ tail -f wild_loop.txtI’ll now go back to my first terminal window, and run the wild_loop1.sh script, like this:
donnie@fedora:~$ ./wild_loop1.sh > wild_loop.txtI 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 fixedcount=25limit=30while [ "$count" -lt "$limit" ];do echo $count (( count = (count + 1)))doneThis time, count is set to 25 and limit is set to 30. Running this script should work better. Let’s see:
donnie@fedora:~$ ./wild_loop2.sh2526272829donnie@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/bashcommand -v Xdialogif [[ $? == 0 ]] && [[ -n $DISPLAY ]]; thendiag=Xdialogelsediag=dialogfi$diag --title "Dialog message box" \--begin 2 2 \--msgbox "\nHowdy folks!" 15 50clearAs 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 ]] 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/bashcommand -v Xdialogif [[ -n $DISPLAY ]] && [[ $? == 0 ]]; thendiag=Xdialogelsediag=dialogfi$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 [[ 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/bashcommand -v Xdialogecho $?sleep 10if [[ -n $DISPLAY ]] && [[ $? == 0 ]]; then diag=Xdialogelse diag=dialogfi$diag --title "Dialog message box" \--begin 2 2 \--msgbox "\nHowdy folks!" 15 50clearI 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:
donnie@fedora:~$ ./xdialog-hello2-broken.sh1The 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/bashcommand -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 50clearRunning the script with this modification looks like this:
donnie@fedora:~$ ./xdialog-hello2-broken.sh0The 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 ? == 0 ]] part? Well, it turns out that 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 for Debugging
Section titled “Using xtrace for Debugging”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 -xcommand -v Xdialogif [[ -n $DISPLAY ]] && [[ $? == 0 ]]; then diag=Xdialog sleep 10else diag=dialog sleep 10fi$diag --title "Dialog message box" \ --begin 2 2 \ --msgbox "\nHowdy folks!" 15 50clearHere, 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.
donnie@fedora:~$ ./xdialog-hello2-broken2.sh+ command -v Xdialog+ [[ -n :0 ]]+ [[ 0 == 0 ]]+ diag=Xdialog+ sleep 10You 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 bashset -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 -xvcommand -v Xdialogif [[ -n $DISPLAY ]] && [[ $? == 0 ]]; thendiag=Xdialogsleep 10elsediag=dialogsleep 10fi$diag --title "Dialog message box" \--begin 2 2 \--msgbox "\nHowdy folks!" 15 50clearHere’s the output:
donnie@fedora:~$ ./xdialog-hello2-broken4.sh#!/bin/bash -xvcommand -v Xdialog<!-- page: 580 (printed 583) -->+ command -v Xdialogif [[ -n $DISPLAY ]] && [[ $? == 0 ]]; then diag=Xdialog sleep 10else diag=dialog sleep 10fi+ [[ -n :0 ]]+ [[ 0 == 0 ]]+ diag=Xdialog+ sleep 10In 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:
donnie@fedora:~$ ./xdialog-hello2-broken4.sh 2> debug.txtWhen 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.
Checking for Undefined Variables
Section titled “Checking for Undefined Variables”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/bashecho "The uninitialized myvar, without setting -u, looks like this : " $myvarechomyvar=Donnieecho "I've just initialized myvar."echo "The value of myvar is: " $myvarHere’s the output:
donnie@fedora:~$ ./unassigned_var1.shThe uninitialized myvar, without setting -u, looks like this :I've just initialized myvar.The value of myvar is: Donniedonnie@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 -uecho "The uninitialized myvar, without setting -u, looks like this : " $myvarechomyvar=Donnieecho "I've just initialized myvar."echo "The value of myvar is: " $myvarLet’s see what this does:
donnie@fedora:~$ ./unassigned_var2.sh./unassigned_var2.sh: line 2: myvar: unbound variabledonnie@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/bashecho "The uninitialized myvar, without setting -u, looks like this : " $myvarechoecho "I'm now setting -u."set -umyvar=Donnieecho "I've just initialized myvar."echo "The value of myvar is: " $myvarechoecho "Let's now try another uninitialized variable."echo "Here's the uninitialized " $myvar2So 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:
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: DonnieLet's now try another uninitialized variable../unassigned_var3.sh: line 11: myvar2: unbound variabledonnie@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/bashmkdir mydircd mydirelsWith 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.
donnie@fedora:~$ ./bad_dir1.sh./bad_dir1.sh: line 4: cd: mydire: No such file or directory15827.zip.zip18.csv2023-08-01_15-23-31.mp4Yeah, 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 -emkdir mydircd mydirelsAll 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.
donnie@fedora:~$ rm -rf mydirdonnie@fedora:~$ ./bad_dir2.sh./bad_dir2.sh: line 4: cd: mydire: No such file or directorydonnie@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 -emkdir mydir && cd mydirelsAs before, I’ll delete the mydir directory that the previous script created, and then run bad_dir3.sh, which looks like this:
donnie@fedora:~$ ./bad_dir3.sh./bad_dir3.sh: line 3: cd: mydire: No such file or directorydonnie@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/bashset -ei=0let 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:
donnie@fedora:~$ ./set_e_fails1.shdonnie@fedora:~$Well, it prints out nothing. Let’s see what happens if I comment out the set -e command, like so:
#!/bin/bash# set -ei=0let i++echo "i is $i"Let’s run it again.
donnie@fedora:~$ ./set_e_fails1.sh<!-- page: 585 (printed 588) -->i is 1donnie@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/bashi=0echo "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:
donnie@fedora:~$ ./set_e_fails2.shExit code after setting the value of i: 0Exit code after incrementing i: 1i is 1Exit code after displaying new value of i: 0donnie@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.
-
You’ll first need to install the autoconf and texinfo packages from your normal distro repository, using your distro’s normal package manager.
-
Download the bashdb source code by doing:
git clone https://github.com/rocky/bashdb.git
-
cd into the bashdb/ directory that the git command created.
-
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.
Debugging a Script with bashdb
Section titled “Debugging a Script with bashdb”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/bashcommand -v Xdialogif [[ -n $DISPLAY ]] && [[ $? == 0 ]]; then diag=Xdialogelse diag=dialogfi$diag --title "Dialog message box" \--begin 2 2 \--msgbox "\nHowdy folks!" 15 50clearAs 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:
donnie@fedora:~$ bashdb ./xdialog-hello2-broken5.shbash debugger, bashdb, release 5.2-1.1.2Copyright 2002-2004, 2006-2012, 2014, 2016-2019, 2021, 2023 Rocky BernsteinThis is free software, covered by the GNU General Public License, and you arewelcome to change it and/or distribute copies of it under certain conditions.(/home/donnie/xdialog-hello2-broken5.sh:3):3: command -v Xdialogbashdb<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:
......bashdb<0> step(/home/donnie/xdialog-hello2-broken5.sh:4):4: if [[ -n $DISPLAY ]] && [[ $? == 0 ]]; thenbashdb<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:
bashdb<1> examine DISPLAYdeclare -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:
bashdb<1> print $DISPLAY:0bashdb<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 ? 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:
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=Xdialogbashdb<4> print $diagbashdb<5> step(/home/donnie/xdialog-hello2-broken5.sh:10):10: $diag --title "Dialog message box" \bashdb<6> print $diagXdialogbashdb<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 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.
Getting Help with bashdb
Section titled “Getting Help with bashdb”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> helpAvailable commands:------------------action complete display export history print search source undisplayalias condition down file info pwd set step untracebacktrace continue edit finish kill quit shell tbreak upbreak debug enable frame list return show trace watchclear delete eval handle load reverse signal tty watchecommands disable examine help next run skip unaliasReadline 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: bbashdb<2>Figure 21.3: Getting help for the break command
That about wraps things up for this chapter. Let’s summarize and move on.
Summary
Section titled “Summary”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.
Questions
Section titled “Questions”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.
- We’ll start with the bug1.sh script:
#!/bin/bashecho "Fix this script...I've got bugs"a=45if [$a -gt 27 ]then- Here’s the bug2.sh script:
#!/bin/bashecho "Fix this script...I've got bugs"for i in 1 2 3 4 5 6 7 8 9doecho $iexit- Now, for bug3.sh:
#!/bin/bashecho "Fix this script...I've got bugs"scripts=$(ls | grep [a-z]*.sh)echo $scriptsexit- Here’s the fourth and final, bug4.sh:
#!/bin/bashecho '1 2 3' > sample.datacut -d' ' -f1,3 sample.data | read x zecho $((x+z))Further Reading
- Writing Shell Scripts—Lesson 9: Stay Out of Trouble: http://linuxcommand.org/lc3_wss0090.php
- How to Debug Bash Scripts: https://linuxconfig.org/how-to-debug-bash-scripts
- 15 Essential Bash Debugging Techniques and Tools: https://www.fosslinux.com/104144/essential-bash-debugging-techniques-and-tools.htm
- Debugging a Bash Script: https://www.baeldung.com/linux/debug-bash-script
- 5 Simple Steps On How to Debug a Bash Shell Script: https://www.shell-tips.com/bash/debug-script/#gsc.tab=0
- Filenames 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
- BashPitfalls: http://mywiki.wooledge.org/BashPitfalls
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/
- Using BashDB to Debug Your Shell Scripts—YouTube: https://www.youtube.com/watch?v=jboQJDSTksA
- BASH Debugger documentation: https://bashdb.sourceforge.net/bashdb.html
- The Bash Trap Trap: https://medium.com/@dirk.avery/the-bash-trap-trap-ce6083f36700
Answers
- In the if statement, you need to insert a blank space between the [ and the $a.
- You need to place a done statement after the echo $i statement.
- 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.
- 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:
donnie@fedora:~$ ./bug4.sh0donnie@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/bashecho '1 2 3' > sample.datacut -d' ' -f1,3 sample.data > tmp.dataread x z < tmp.dataecho $((x+z))Another option would be to use a here document, as you see in the bug6.sh script:
#!/bin/bashecho '1 2 3' > sample.dataread -r x z <<<$(cut -d' ' -f1,3 sample.data)echo $((x+z))Either way, you’ll now see the correct results:
donnie@fedora:~$ ./bug5.sh4donnie@fedora:~$ ./bug6.sh4donnie@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.