BASH step-debugging using 'trap'
BASH step-debugging using 'trap'
- bash - The standard command line terminal commonly used in Linux, others are ash, and rsh.
- Full compliments and notice shoutout to sysxplore for pointing out this powerful technique.
#!/bin/env bash
trap 'echo "[${BASH_SOURCE}:${LINENO}] $BASH_COMMAND" ; read -p "Continue?"' DEBUG
file="/tmp/sample.txt"
touch "$file"
echo "Sample data" > "$file"
echo "Displaying contents of $file"
cat "$file"
echo "Removing $file"
rm "$file"
Note that the line numbers visible in the image (e.g., 1, 3, 5, etc.) appear to skip blanks, suggesting possible empty lines in the editor view, but the functional code remains as shown above.
Explanation of the Script
This script serves as a demonstration of Bash debugging techniques, specifically utilizing the trap command to implement a simple step-through debugger. It performs basic file operations on a temporary file while pausing execution between commands to allow user interaction. Below is a detailed, line-by-line breakdown of its structure and functionality, assuming execution in a Unix-like environment with Bash.
Shebang Line (#!/bin/env bash):
This specifies the interpreter for the script. It directs the system to execute the script using the Bash shell located via the env utility, ensuring portability across systems where Bash may be installed in different paths.
Trap Command (trap 'echo "[${BASH_SOURCE}:${LINENO}] $BASH_COMMAND" ; read -p "Continue?"' DEBUG):
This is the core debugging mechanism. The trap built-in sets a handler for the DEBUG signal, which Bash emits before executing each command in the script (after this line). The handler performs two actions:
echo "[${BASH_SOURCE}:${LINENO}] $BASH_COMMAND": Prints the script's source file name (${BASH_SOURCE}), the current line number (${LINENO}), and the command about to be executed ($BASH_COMMAND). This provides visibility into the script's flow.read -p "Continue?": Prompts the user with "Continue?" and waits for input (typically Enter) before proceeding. This effectively creates a step-by-step execution mode, useful for debugging.
TheDEBUGtrap does not affect the shebang line but applies to all subsequent commands.
Variable Declaration (file="/tmp/sample.txt"):
Defines a variable file holding the path to a temporary file in the /tmp directory, which is a standard location for transient files on Unix systems. The use of double quotes ensures proper handling of the path.
Create File (touch "$file"):
Uses the touch command to create an empty file at the specified path if it does not exist, or update its timestamp if it does. The variable is quoted to prevent issues with special characters.
Write to File (echo "Sample data" > "$file"):
Outputs the string "Sample data" and redirects it (>) to overwrite the contents of the file. This populates the file with simple text content.
Display Message (echo "Displaying contents of $file"):
Prints a descriptive message to standard output, interpolating the value of $file to inform the user of the upcoming action. Note that the variable is not quoted here, but in this context, it is safe due to the absence of spaces or special characters.
Display File Contents (cat "$file"):
Uses the cat command to concatenate and print the file's contents to standard output. This verifies the data written in the previous step.
Display Message (echo "Removing $file"):
Prints another informative message, similar to line 6, indicating the next operation.
Remove File (rm "$file"):
Deletes the file using the rm command. The file path is quoted for safety. This cleans up the temporary file, preventing accumulation in /tmp.
Overall Behavior and Execution Flow
When executed (e.g., via bash demo.sh), the script runs in a debug mode due to the trap. Before each command after the trap declaration, it will output a line like [demo.sh:5] file="/tmp/sample.txt" (where "demo.sh" is the script name, 5 is the line number, and the rest is the command), followed by the prompt "Continue?". The user must press Enter to proceed to the next step. This allows for manual inspection and control, making it an effective tool for tracing script execution.
The script's primary purpose is educational or demonstrative, showcasing file manipulation (create, write, read, delete) while highlighting Bash's built-in debugging capabilities. It assumes write permissions in /tmp and does not include error handling (e.g., for failed commands), which would be advisable in production scripts. If run without sufficient privileges or if the file cannot be created, it may produce errors, but the trap will still trigger for visibility.