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.

outcome
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"
  1. outcome ← fail

    3outcome="fail"4temp_dir="tmp/run"
    values this stepfailoutcome
  2. temp_dir ← tmp/run

    3outcome="fail"4temp_dir="tmp/run"5cleanup="rm -rf $temp_dir"
    values this steptmp/runtemp_dir
  3. cleanup ← rm -rf tmp/run

    4temp_dir="tmp/run"5cleanup="rm -rf $temp_dir"6if [ "$outcome" = "ok" ]; then
    values this steprm -rf tmp/runcleanuptmp/runtemp_dir
  4. if [ "$outcome" = "ok" ]; then

    5cleanup="rm -rf $temp_dir"6if [ "$outcome" = "ok" ]; then7    exit_code=0
    values this stepfailoutcome
  5. exit_code ← 1

    8else9    exit_code=110fi
    values this step1exit_code
  6. echo "$cleanup after $outcome exit=$exit_code"

    10fi11echo "$cleanup after $outcome exit=$exit_code"
    outputrm -rf tmp/run after fail exit=1
    values this steprm -rf tmp/runcleanupfailoutcome1exit_code
  1. outcome ← ok

    3outcome="ok"4temp_dir="tmp/run"
    values this stepokoutcome
  2. temp_dir ← tmp/run

    3outcome="ok"4temp_dir="tmp/run"5cleanup="rm -rf $temp_dir"
    values this steptmp/runtemp_dir
  3. cleanup ← rm -rf tmp/run

    4temp_dir="tmp/run"5cleanup="rm -rf $temp_dir"6if [ "$outcome" = "ok" ]; then
    values this steprm -rf tmp/runcleanuptmp/runtemp_dir
  4. if [ "$outcome" = "ok" ]; then

    5cleanup="rm -rf $temp_dir"6if [ "$outcome" = "ok" ]; then7    exit_code=0
    values this stepokoutcome
  5. exit_code ← 0

    6if [ "$outcome" = "ok" ]; then7    exit_code=08else
    values this step0exit_code
  6. echo "$cleanup after $outcome exit=$exit_code"

    10fi11echo "$cleanup after $outcome exit=$exit_code"
    outputrm -rf tmp/run after ok exit=0
    values 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.