I've tried to use trap
to remove a temporary file at the end of a Bourne shell script, but this doesn't work:
trap "trap \"rm \\\"$out\\\"\" EXIT INT TERM" 0
This is inside a function, by the way, hence the attempt at a nested trap.
How do I do it?
You can only have one trap set for each signal. If different parts of your script need to perform different cleanup actions, you’ll have to create lists of cleanup actions. Then set a single trap handler that performs all the required cleanup actions.
Here’s an example:
There’s a single trap handler, but you can register cleanup actions from anywhere in the script by appending to the
TEMP_FILES
array. The cleanup actions can be registered from inside functions too.If you’re not using a shell with arrays, the basic idea is the same, but the implementation details will be a little bit different. For example, you could store the list as a colon-separated string variable, using the
${parameter%%word}
expansions in every POSIX shell to iterate through its elements in the trap handler: