I'm wondering if something like this is possible.
function get_temp_dir() {
local tmp_dir=$(mktemp -d)
trap "{
rm -r $tmp_dir
}" EXIT
echo $tmp_dir
}
temp=$(get_temp_dir)
# I'd like to $temp for the duration of this script, and deleted
# when this current scope ends, not when the function scope ends.
I've seen other scripts achieve the same effect using global arrays with a single trap function that enumerates the array and does something with it. I'd like to avoid that if I can.
I'm also aware that I could just create one tmp directory, and create multiple tmp directories within said directory. However, I'd like to use this approach because it is broadly usable for other things, such as mount/unmount.
Any ideas? Thanks in advance.
edit: So, TRAP does get called when the shell script ends, however, in my original question, I was using a subshell ($()
). I got it working after reformatting my code to this:
#!/usr/bin/env bash
function get_temp_dir() {
local tmp_dir=$(mktemp -d)
trap "{
rm -r $tmp_dir
}" EXIT
retval=$tmp_dir
}
get_temp_dir
tmp_dir=$retval
ls $tmp_dir
EXIT
trap fire when the shell exits, not when the function returns? Isn't that what you want, apart from the fact that you can only have oneEXIT
trap at a time? The workaround for that could indeed be a single trap that runs any and all necessary cleanup commands that could be stored in an array or such, just as you say.bash -c 'set_trap() { trap "echo trap >&2" EXIT; }; : $(set_trap); echo end;'
printstrap
and thenend
. Which sort of means that you can't set a useful trap in a function you call from$()
(and neither could you add the cleanup code to an array, since that also wouldn't show up in the main shell.)