gpt4 book ai didi

退出函数时的 Bash 陷阱

转载 作者:行者123 更新时间:2023-11-29 08:49:06 31 4
gpt4 key购买 nike

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 bashtrap 内建函数的描述:

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.

关于退出函数时的 Bash 陷阱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45862044/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com