Shell Script · Lesson

Shell Scripting · Lesson 18

Debugging & Traps in Shell Scripting

Add YouTube embed URL in components/shell/ShellLessons.js

What is Debugging?

Debugging is the process of finding and fixing errors in a script. Shell provides built-in tools to help trace execution and handle failures.

Why Debugging is Important?

Error Detection

Detect errors early during execution.

Stability

Prevent scripts from crashing silently.

Reliability

Improve script reliability and safety.

Debugging Tools in Shell

  • set -x – Print commands before execution
  • set -e – Exit on error
  • set -u – Treat unset variables as errors
  • trap – Catch signals and cleanup

Debugging Examples

1. Debug Mode with set -x

Prints each command before executing it.

terminal — bash
debug
#!/bin/bash
set -x
 
name="Linux"
echo "Hello $name"

2. Exit on Error (set -e)

Stops script execution when a command fails.

terminal — bash
debug
#!/bin/bash
set -e
 
mkdir testdir
cd testdir2 # This will fail
echo "This line will not run"

3. Unset Variable Check (set -u)

Treats unset variables as errors.

terminal — bash
debug
#!/bin/bash
set -u
 
echo $UNDEFINED_VAR

4. Trap Signals

Execute commands when script exits or receives signals.

terminal — bash
debug
#!/bin/bash
 
trap "echo 'Script interrupted'; exit" SIGINT
 
while true
do
echo "Running..."
sleep 2
done

Best Practices

Debugging Tips

  • Use set -e in production scripts.
  • Use trap to clean up temporary files.
  • Test scripts with invalid inputs.
  • Remove debug output before production.

Practice Task – Debugging

  • Create a script that exits on error.
  • Use trap to catch Ctrl+C.
  • Enable debug mode and observe output.

Next lesson: Logging & Redirection