2022年10月8日(土) 12:04 Cynthia Coan <cynt...@coan.dev>: > [...] > > Otherwise, I think we can perhaps reword this into two smaller > features: "function local trap signals",
The existing RETURN trap is exactly the trap that can be used to clean up resources local to functions and is already ``function-local'' unless the user changes its behavior by setting `declare -ft', `set -T', or `shopt -s extdebug'. One thing to note is that the RETURN trap should be cleaned up inside the RETURN trap itself by running `trap - RETURN', or otherwise the RETURN trap is erroneously considered by Bash to be set for the caller function. > and "options to safely > append/prepend to a trap" (for some definition of 'safe', perhaps this > just means separating by ';'? Currently, there is no way to register multiple handlers to a trap in a safe way, but if you can accept the approach by `;' or newline, you can just do it by getting the current trap string with `trap -p RETURN' and then overwrite the trap with the adjusted trap string. If you don't want to write such a code every time, you can write a shell function to perform that. In that case, be careful that the function needs to be marked with the trace attribute by ``declare -ft <function-name>''. Also, the RETURN trap needs to be suppressed for such a function itself. I haven't really tested it but something like this should work as you expect: function defer { local command=$1 trap eval "trap=($(trap -p RETURN))" if [[ $trap ]]; then trap[2]=$command$'\n'${trap[2]} else trap=(trap -- "$command" RETURN) fi trap[2]='if [[ $FUNCNAME != defer ]]; then '${trap[2]}$'\ntrap - RETURN\nfi' "${trap[@]}" } declare -ft defer The above `defer' function effectively "eval"s the first argument through `trap', so you need to specify in the following way: defer 'rm -r "${tmp_dir}"' defer 'set +e' defer 'set +o pipefail' Another thing to note is that the RETURN trap will be skipped when Bash receives SIGINT, so if you want to properly perform the clean up even when your Bash program receives SIGINT, you need to additionally set the SIGINT handler in a proper way. -- Koichi