Shell Scripting in 2 Weeks — Day #7
Exit Status & Error Handling
When writing shell scripts, handling errors properly is crucial to avoid unexpected failures and improve script reliability. Let’s break it down:
🔹 What is an Exit Status in Shell?
Every command executed in a shell script returns an exit status code:
✅ 0 → Success
❌ Non-zero → Failure (Different numbers indicate different errors)
Check the last command’s exit status using:
Get Devops Diaries’s stories in your inbox
Join Medium for free to get updates from this writer.
echo $? # Prints the exit status of the last command
🔹 Handling Exit Status
Use conditional checks to handle errors:
if command; then
echo “Success!”
else
echo “Failure!”
fi🔹 Using set -e for Automatic Error Handling
Adding set -e at the beginning of a script makes it exit immediately if any command fails:
#!/bin/bash
set -e # Script exits on the first errormkdir /testdir # Fails if permission denied
echo “This won’t execute if mkdir fails”🛑 Warning: Be careful with set -e in loops or conditional statements, as it may cause unexpected exits.
🔹 Using trap for Cleanup & Debugging
trap allows you to execute a function when the script exits or encounters a signal. Useful for cleanup tasks.
#!/bin/bash
trap ‘echo “Script failed at line $LINENO”; exit 1’ ERR # Catch errorsmkdir /testdir
rm -rf /testdir # Ensures cleanup even on failure🎯 Key Takeaways:
✅ Use exit codes to track command success/failure.
✅ Use set -e to stop execution on errors.
✅ Use trap to catch errors and clean up resources.
Do you use these techniques in your shell scripts? Share your thoughts! 👇









