Sometimes you may find yourself in a situation where you need to actually debug a shell script you're currently writing. Especially in the initial phase of development, features like single-stepping feel quite handy.

I this article we are going to look at two situations where the bash debugger (bashdb) is a great tool for shell scripting. I will also show you one bashdb feature I find really surprising.

Scenario A

Imagine a situation where you'd like to create a list of files and apply an operation on each of them afterwards. During debugging the script, you might feel the need to comment out some lines containing potentially dangerous statements to prevent operations on the wrong files.

Scenario B

The second scenario I've identified is also related to debugging. Sometimes I don't want to execute an entire script altogether but rather like to execute one line after another and check its particular effect on the (file) system. I would then usually place a read statement before each critical line so I can either break out (using Ctrl-C) or continue execution.

As I've found out, both scenarios can be handled in an elegant way by using the bash debugger. Let's consider the following bash script:

#!/bin/bash
function dangerousOperation() {
    echo "$1"
}

echo "Generating file list..."
files=$(ls /etc)
echo "Executing operation (potentially dangerous)..."
dangerousOperation "$files"

Note that the 'dangerous' operation is replaced by a harmless echo command in this case. According to scenario A, I would usually comment out the call to dangerousOperation() until I'm sure that the list of files generated is correct. For scenario B, a read right before that line would do.

To demonstrate how the bash debugger can help here, I've prepared a short screencast for you:

Surprising for me is the skip command. Note that the function call hasn't been executed at all in this example!

These are the commands used in the screencast:

  • list
  • step
  • skip

Some other commands and combinations worth checking:

  • restart
  • print $foo
  • help
  • continue
  • list list
  • step 3
  • break

Please refer to the bashdb docs for detailed information. You can get the bash debugger via that package manager of your system, e.g. apt-get install bashdb.

Do you have any experience with the bashdb? Please contact me on twitter: @ronalterde.