0
0
Bash-scriptingDebug / FixBeginner · 3 min read

How to Debug Bash Script: Simple Steps to Find Errors

To debug a bash script, run it with bash -x script.sh to see each command executed with its arguments. You can also add set -x inside the script to enable debugging from that point onward.
🔍

Why This Happens

Bash scripts often fail silently or behave unexpectedly because commands run without showing what is happening step-by-step. This makes it hard to see where the script goes wrong.

bash
#!/bin/bash

name=John
if [ "$name" = "John" ]
then
  echo "Hello, $name"
fi
🔧

The Fix

Enable debugging to see each command and its arguments as the script runs. Use bash -x script.sh from the terminal or add set -x inside the script before the code you want to debug.

bash
#!/bin/bash

set -x
name=John
if [ "$name" = "John" ]
then
  echo "Hello, $name"
fi
Output
+ name=John + '[' John = John ']' + echo 'Hello, John' Hello, John
🛡️

Prevention

Always quote variables in conditions to avoid errors from spaces or empty values. Use set -e to stop the script on errors and set -u to catch unset variables. Regularly run your script with bash -n to check syntax without executing.

⚠️

Related Errors

Common errors include unquoted variables causing word splitting, missing fi for if blocks, and commands failing silently. Using set -x helps spot these quickly.

Key Takeaways

Use bash -x script.sh to see commands as they run for easy debugging.
Add set -x inside scripts to enable step-by-step tracing.
Quote variables in conditions to prevent unexpected errors.
Use set -e and set -u to catch errors early.
Run bash -n to check script syntax without running it.