Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash trap on exit from function

Tags:

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.

like image 698
bercik Avatar asked Aug 24 '17 12:08

bercik


People also ask

What is trap exit in bash?

The secret sauce is a pseudo-signal provided by bash, called EXIT, that you can trap; commands or functions trapped on it will execute when the script exits for any reason.

How do you use traps in bash?

To set a trap in Bash, use trap followed by a list of commands you want to be executed, followed by a list of signals to trigger it. For complex actions, you can simplify trap statements with Bash functions.

How do I interrupt in bash?

There are many methods to quit the bash script, i.e., quit while writing a bash script, while execution, or at run time. One of the many known methods to exit a bash script while writing is the simple shortcut key, i.e., “Ctrl+X”. While at run time, you can exit the code using “Ctrl+Z”.

What is bash set E?

Set –e is used within the Bash to stop execution instantly as a query exits while having a non-zero status. This function is also used when you need to know the error location in the running code.


1 Answers

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.

like image 200
Aaron Avatar answered Sep 25 '22 08:09

Aaron