Bash 函数退出时陷入陷阱
Bash trap on exit from function
在 bash 中是否可以在函数退出时调用一些命令。我的意思是:
function foo
{
# something like this maybe?
trap "echo \"exit function foo\"" EXIT
# do something
}
foo
我想打印出退出函数 foo。
是的,你可以设陷阱 RETURN
:
$ function foo() {
> trap "echo finished" RETURN
> echo "doing some things"
> }
$ foo
会显示
doing some things
finished
来自 man 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.
关于使用 Ctrl+c 退出(不声明另一个退出函数):
#!/bin/bash
function do_stuff() {
function do_stuff_end() {
# the code for exiting the function here
echo "<the code for exiting the function here>"
unset -f do_stuff_end
trap "$trap_sigint" SIGINT
return
}
trap_sigint="$(trap -p SIGINT)"
trap "do_stuff_end; return" SIGINT
# the code for the function here
echo "<the code for the function here>"
do_stuff_end
}
N.B.: 前面的代码“只是”工作但需要通过考虑 SIGINT
以外的其他信号的影响来改进
在 bash 中是否可以在函数退出时调用一些命令。我的意思是:
function foo
{
# something like this maybe?
trap "echo \"exit function foo\"" EXIT
# do something
}
foo
我想打印出退出函数 foo。
是的,你可以设陷阱 RETURN
:
$ function foo() {
> trap "echo finished" RETURN
> echo "doing some things"
> }
$ foo
会显示
doing some things
finished
来自 man 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.
关于使用 Ctrl+c 退出(不声明另一个退出函数):
#!/bin/bash
function do_stuff() {
function do_stuff_end() {
# the code for exiting the function here
echo "<the code for exiting the function here>"
unset -f do_stuff_end
trap "$trap_sigint" SIGINT
return
}
trap_sigint="$(trap -p SIGINT)"
trap "do_stuff_end; return" SIGINT
# the code for the function here
echo "<the code for the function here>"
do_stuff_end
}
N.B.: 前面的代码“只是”工作但需要通过考虑 SIGINT
以外的其他信号的影响来改进