Signals and Job Control Concepts
Trap Plan
Build a Cleanup Command
trap registers a command to run later, commonly on script exit. Planning the command as text makes cleanup behavior reviewable.
Program
Play the script to choose the cleanup target and build the trap command that would be registered.
trap_plan.sh
#!/usr/bin/env bash
cleanup_target=
trap_command="rm -rf /tmp/$cleanup_target"
signal="EXIT"
plan="trap '$trap_command' $signal"
echo "$plan"
#!/usr/bin/env bash
cleanup_target=
trap_command="rm -rf /tmp/$cleanup_target"
signal="EXIT"
plan="trap '$trap_command' $signal"
echo "$plan"
#!/usr/bin/env bash
cleanup_target=
trap_command="rm -rf /tmp/$cleanup_target"
signal="EXIT"
plan="trap '$trap_command' $signal"
echo "$plan"
trap
`trap 'command' EXIT` registers cleanup for script exit.
cleanup target
Keeping the target in a variable makes the final cleanup command visible.
command plan
This example prints a plan instead of deleting files.