bashfunctionexit

Bash trap on exit from function


Is there possible in bash to call some command when function exits. I mean something like:

function foo
{
    # something like this maybe?
    trap "echo \"exit function foo\"" EXIT

    # do something
}

foo

And i want exit function foo to be printed out.


Solution

  • 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.