Sitemap
DevOps.dev

Devops.dev is a community of DevOps enthusiasts sharing insight, stories, and the latest development in the field.

Shell Scripting in 2 Weeks — Day #7

Exit Status & Error Handling

2 min readFeb 24, 2025

--

When writing shell scripts, handling errors properly is crucial to avoid unexpected failures and improve script reliability. Let’s break it down:

Press enter or click to view image in full size
Exit Status & Error Handling

🔹 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 error
mkdir /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 errors
mkdir /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! 👇

--

--

Published in DevOps.dev

Devops.dev is a community of DevOps enthusiasts sharing insight, stories, and the latest development in the field.