退出函数时的 Bash 陷阱

标签 bash function exit

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/

相关文章:

bash - ECS/Fargate 容器定义命令参数

linux - Bash 路径计算

c++ - 从 exe 入口点返回不会终止 Windows 10 上的进程

python - 如何告诉 Python 中的 lambda 函数返回 None 而不是抛出键值错误

python - python 中的汉诺塔与 turtle 图形移动磁盘

c - 确定我的应用程序是否由于调用 _exit() 而终止

python - 用户输入 Exit 以中断 while 循环

unix - 单引号在 shell 脚本中不起作用

bash - 有人可以用简单的英语解释这个简短的 getopts bash 脚本吗? (UNIX)

javascript - 我如何制作这个简单的 JavaScript 函数?