Module 6: Robust Scripting
In production, a script that fails silently is a disaster. Today, you'll learn how to make your scripts "fail fast" and clean up after themselves.
Step 1: The 'Fail Fast' (set -e)
By default, Bash keeps running even if a command fails. This can lead to corrupted data. The set -e command tells Bash to exit immediately if any command returns a non-zero exit code.
Mission: Create a file called script.sh and add set -e at the top.
Step 2: The Cleanup Crew (trap)
What if your script creates a temporary file and then crashes? The trap command allows you to execute a "cleanup" function whenever the script exits, even if it fails.
Example:
cleanup() {
rm -f /tmp/temp_data
}
trap cleanup EXIT
Mission: Add a trap command to your script.sh that calls a cleanup function.
booting...