Bash trap when exiting function

Is it possible in bash to call some command when exiting a function. I mean something like:

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

    # do something
}

foo

And I want the foo exit function to be printed.

+4
source share
1 answer

Yes, you can capture RETURN:

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

Will display

doing some things
finished

From the man bashdescription of trapbuiltin:

If sigspec is RETURN, the arg command is executed every time a shell or script function is executed that is executed with. or inline source functions complete execution.

+5
source

Source: https://habr.com/ru/post/1684377/


All Articles