Bash trap on exit from function

Yes, you can trap RETURN :

$ function foo() {
>   trap "echo finished" RETURN
>   echo "doing some things"
> }
$ foo

Will display

doing some things
finished

From man bash‘s description of the trap builtin :

If a sigspec is RETURN, the command arg is executed each time a shell function or a script executed with the . or source builtins finishes executing.

Leave a Comment

tech