退出函数时的 Bash 陷阱
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45862044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash trap on exit from function
提问by bercik
Is there possible in bash to call some command when function exits. I mean something like:
当函数退出时,bash 是否可以调用一些命令。我的意思是这样的:
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.
我想打印出退出函数 foo 。
回答by Aaron
Yes, you can trap RETURN
:
是的,您可以捕获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 :
Fromman bash
对trap
内置函数的描述:
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.
如果 sigspec 是 RETURN,则每次使用 . 或源内置函数完成执行。