Bash Debugging
Debugging is the work of finding and fixing errors in a script. Bash has built-in tools that check syntax, trace commands, and stop on failure.
Check syntax with bash -n
This small script is missing its closing fi. Bash reports the error line on stderr, and nothing from the script runs.
echo 'echo "Start"' > broken.sh
echo 'if [ 1 -eq 1 ]; then' >> broken.sh
echo ' echo "Inside"' >> broken.sh
bash -n broken.shA script with good syntax
A script with no syntax errors prints nothing under bash -n. The exit status 0 shows the check passed.
echo 'echo "Hello"' > good.sh
bash -n good.sh
echo $?Trace commands with set -x
Trace lines start with + and go to stderr. Shown here, the trace lines and the normal output appear together in run order.
name="Ana"
set -x
echo "Hello, $name"
echo "Done"Example
set -e
echo "First line runs"
false
echo "This line never prints"Key points
- The bash -n command checks a script for syntax errors without running it.
- A syntax error message names the file and describes the problem.
- The set -x command traces each command before Bash runs it.
- Trace lines start with a + sign and go to stderr.
- The set -e command stops a script at the first failing command.
- Checking syntax first saves time when a script will not start at all.
In this example, set -e stops the script as soon as the false command fails. The first echo prints, and the last echo never runs. Only one line of output appears.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does bash -n script.sh do?