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
Replay: real traced execution (multi-file project)
#!/usr/bin/env bash
outcome="fail"
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="ok"
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"
outcome ← fail
3outcome="fail"4temp_dir="tmp/run"values this stepfailoutcometemp_dir ← tmp/run
3outcome="fail"4temp_dir="tmp/run"5cleanup="rm -rf $temp_dir"values this steptmp/runtemp_dircleanup ← rm -rf tmp/run
4temp_dir="tmp/run"5cleanup="rm -rf $temp_dir"6if [ "$outcome" = "ok" ]; thenvalues this steprm -rf tmp/runcleanuptmp/runtemp_dirif [ "$outcome" = "ok" ]; then
5cleanup="rm -rf $temp_dir"6if [ "$outcome" = "ok" ]; then7 exit_code=0values this stepfailoutcomeexit_code ← 1
8else9 exit_code=110fivalues this step1exit_codeecho "$cleanup after $outcome exit=$exit_code"
10fi11echo "$cleanup after $outcome exit=$exit_code"outputrm -rf tmp/run after fail exit=1values this steprm -rf tmp/runcleanupfailoutcome1exit_code
outcome ← ok
3outcome="ok"4temp_dir="tmp/run"values this stepokoutcometemp_dir ← tmp/run
3outcome="ok"4temp_dir="tmp/run"5cleanup="rm -rf $temp_dir"values this steptmp/runtemp_dircleanup ← rm -rf tmp/run
4temp_dir="tmp/run"5cleanup="rm -rf $temp_dir"6if [ "$outcome" = "ok" ]; thenvalues this steprm -rf tmp/runcleanuptmp/runtemp_dirif [ "$outcome" = "ok" ]; then
5cleanup="rm -rf $temp_dir"6if [ "$outcome" = "ok" ]; then7 exit_code=0values this stepokoutcomeexit_code ← 0
6if [ "$outcome" = "ok" ]; then7 exit_code=08elsevalues this step0exit_codeecho "$cleanup after $outcome exit=$exit_code"
10fi11echo "$cleanup after $outcome exit=$exit_code"outputrm -rf tmp/run after ok exit=0values this steprm -rf tmp/runcleanupokoutcome0exit_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.