trap
CommandDebugging is crucial when your script isnβt behaving as expected. Bash provides built-in tools like set -x
, trap
, and line tracing to help identify bugs.
set
set -x
Print each command and its arguments as they execute.
#!/bin/bash
set -x
name="Kashif"
echo "Hello, $name"
Output:
+ name=Kashif
+ echo 'Hello, Kashif'
Hello, Kashif
set +x
Turn off debugging.
set -x
echo "Debugging"
set +x
echo "No debug"
trap
β Capture Script Eventstrap 'commands' SIGNAL
Common Signals:
Signal | Meaning |
---|---|
EXIT |
When script exits |
ERR |
On any error (use with set -e ) |
INT |
Ctrl+C interrupt |
DEBUG |
Before every command |
#!/bin/bash
trap 'rm -f /tmp/tempfile' EXIT
touch /tmp/tempfile
echo "Working..."
sleep 3
exit 0
Even if the script fails or is killed, /tmp/tempfile
will be removed.
#!/bin/bash
set -e
trap 'echo "β Error on line $LINENO"; exit 1' ERR
cp file.txt /nonexistent/dir
Output:
β Error on line 5
#!/bin/bash
trap 'echo "Running line: $BASH_COMMAND"' DEBUG
echo "Line 1"
ls /invalid/path
echo "Line 3"
Useful for deep debugging.
#!/bin/bash
set -euo pipefail
trap 'echo "Error on line $LINENO: $BASH_COMMAND"; exit 1' ERR
trap 'echo "Finished script"; exit 0' EXIT
trap 'echo "Interrupted by user"' INT
echo "Starting work..."
# Simulated error
cp file.txt /root/
Practice | Benefit |
---|---|
Use set -euo pipefail |
Safer scripts |
Trap ERR and EXIT |
Cleanup and error logs |
Debug with set -x |
Trace issues easily |
Use logging functions | Record errors in a log file |
π File:
advance/debug-trap.md
Author: Kashif Alam