Bash Script Debugging

Bash, the powerful command-line interface for Linux and Unix systems, doesn’t leave you in the dark when it comes to troubleshooting your scripts. This post will guide you through essential debugging techniques using Bash options and commands, helping you pinpoint and resolve errors efficiently.

Bash Debugging Options

1. The -x Option: Trace Your Steps

Running your script with bash -x your_script.sh enables tracing mode. Bash will echo each command before it’s executed, revealing the flow of your script and values of variables.

a=5
b=10
echo $((a + b))

Running it with bash -x will produce the following output:

+ a=5
+ b=10
+ echo 15
15

2. The -n Option: Syntax Check

bash -n your_script.sh performs a syntax check without running the script. It’s helpful for catching typos and structural errors.Example:

if [ $a -gt 5 ]  # Missing the 'then' keyword 
  echo "a is greater than 5"
fi

Running it with bash -n will give a syntax error:

syntax error near unexpected token 'echo'

3. The -u Option (or set -u): Unbound Variable Detection

Using bash -u or set -u within your script triggers an error if you try to use a variable that hasn’t been assigned a value. This is a fantastic way to catch misspellings or logic errors.Example:

#!/bin/bash
set -u

echo "Value of unassigned_variable: $unassigned_variable" 

Running this script will produce an error.

Additional Debugging Techniques

  • Echo Statements: Strategically place echo commands to print variable values or progress messages.
  • The tee Command: Insert tee output_file.txt in a pipe to capture intermediate results without disrupting the flow.

Example: Debugging with set

#!/bin/bash
set -u  # Unbound variable check
set -x  # Tracing mode

a=10
echo "My PID is $$" 

set +x  # Disable tracing
b=20    # This line won't be traced

set -x  # Enable tracing again
echo "a + b + c = $((a + b + c))"  # Will trigger an error due to 'c' being unset

Key Takeaways

  • bash -x is your script’s story-teller, revealing its every move.
  • bash -n acts as a grammar checker, ensuring your syntax is sound.
  • set -u is your safety net, alerting you to potential unbound variable errors.

Combine these techniques with well-placed echo statements and the tee command, and you’ll become a Bash debugging ninja!