Error handling and debugging are crucial practices in shell scripting that ensure scripts run reliably and issues are quickly identified and resolved.
Effective error handling allows a script to respond gracefully to unexpected situations, while debugging tools help pinpoint the root causes of problems. Mastering these techniques leads to more robust and maintainable automation.
Error Handling Techniques
Detecting and responding to errors in scripts preserves stability and allows controlled script termination or recovery.
Check exit status ($?): Every command returns an exit code where 0 indicates success, and non-zero signals failure.
mkdir /root/testdir
if [ $? -ne 0 ]; then
echo "Failed to create directory"
exit 1
fiset -e: Causes the script to exit immediately if any command fails, useful in critical automation.
#!/bin/bash
set -e
command1
command2 # If this fails, script exits immediately|| and && Operators: Execute commands conditionally:
mkdir /tmp/mydir && echo "Created" || echo "Failed"trap Command: Defines a handler executed on errors or signals.
trap 'echo "Error occurred! Cleaning up..."; exit 1' ERRDebugging helps trace script execution and identify variable states or logic errors.
1. set -x: Enables command tracing, printing each command before execution.
#!/bin/bash
set -x
echo "Debug mode on"2. set -v: Prints shell input lines as they are read.
3. Use combined set -xv for detailed tracing.
4. echo statements: Inserted in scripts to print variable values or checkpoints.
5. Debugging tools: Tools like bashdb provide step-through debugging with breakpoints.
6. Run script with debug flag:
bash -x script.shCommon Troubleshooting Tips
1. Validate script syntax with shellcheck or linting tools.
2. Review error messages and line numbers.
3. Isolate segments to test individual parts.
4. Use logging by redirecting output to log files:
./script.sh > script.log 2>&1-Picsart-CropImage.png)