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.
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.
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.
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”.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With