Process Exit and Recovery
Cleanup on Exit
Plan the Final Step
Cleanup should happen after success and failure. This example models the cleanup command and exit code instead of running a real trap.
Program
Play the script to choose the outcome and see the cleanup summary.
cleanup_exit_plan.sh
#!/usr/bin/env bash
outcome=
temp_dir="tmp/run"
cleanup="rm -rf $temp_dir"
if [ "$outcome" = "ok" ]; then
exit_code=0
else
exit_code=1
fi
echo "$cleanup after $outcome exit=$exit_code"
#!/usr/bin/env bash
outcome=
temp_dir="tmp/run"
cleanup="rm -rf $temp_dir"
if [ "$outcome" = "ok" ]; then
exit_code=0
else
exit_code=1
fi
echo "$cleanup after $outcome exit=$exit_code"
cleanup
Cleanup removes temporary work after the main flow ends.
exit code
The exit code records whether the process should be treated as success or failure.
trap concept
Real scripts often use traps for cleanup; this lesson models the final action without running one.