On Sat, Oct 8, 2022, at 2:11 AM, Koichi Murase wrote: > 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.
The latter behavior is why I didn't describe RETURN as function-local in my earlier message, but I forgot the workaround of unsetting the trap from within itself. Nice. >> 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. Another strategy is to construct the complete trap string before setting the trap, using whichever concatenation methods are preferred: f() { local trapcmds=cleanup if something; then trapcmds+='; more_cleanup' else trapcmds+='; so_fresh_and_so_clean' fi trap "$trapcmds; trap - RETURN" RETURN rest_of_function } -- vq