Shell Debugging Scripts
Shell debugging means tracking down mistakes in a script and fixing them. Two built-in tools help: bash -n checks the script, and set -x shows each command as it runs.
Check a script first
bash -n reads a script and reports syntax errors. It runs nothing.
cat > check.sh << 'EOF'
echo "Hello Ana"
EOF
bash -n check.sh
echo "No errors found."A script with a mistake
The check names the file and the line. The missing fi is the mistake.
cat > bad.sh << 'EOF'
echo "Starting backup"
if [ -f notes.txt ]; then
echo "Notes found"
EOF
bash -n bad.sh 2>&1
echo "Check finished."Trace each command
set -x prints each command before it runs. Each trace line starts with +.
cat > trace.sh << 'EOF'
set -x
echo "Starting"
name="Ana"
echo "Hello $name"
echo "Done"
EOF
bash trace.sh 2>&1Stop at the first failure
set -e stops a script when a command fails. The last line never runs.
cat > fail.sh << 'EOF'
set -e
echo "first"
false
echo "never printed"
EOF
bash fail.sh
echo "Script stopped."Example
cat > greet.sh << 'EOF'
#!/bin/bash
set -x
name="Ana"
echo "Hello $name"
echo "Done"
EOF
bash -n greet.sh && echo "Syntax OK"
bash greet.sh 2>&1Key points
- bash -n: a check that reads a script for mistakes without running it.
- Use bash -n before you run a script you have just changed.
- set -x: a setting that prints each command before the shell runs it.
- Use set -x to trace a script that behaves in a strange way.
- The trace lines start with a plus sign, so you can tell them apart from real output.
- set -e: a setting that stops a script at the first command that fails.
- ShellCheck: a tool that checks shell scripts for common mistakes. Install it, then run it on a script.
In this example, bash -n checks greet.sh first and reports Syntax OK. Then the script runs with set -x, so each command is traced with a + line before its output.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does bash -n script.sh do?