Pet*_*etr 4 linux script bash zsh shell-script
我需要编写一个zsh具有多个退出点的函数,并在每个退出点处执行相同的清理命令:
function foo {
if ... ; then
...
run_cleanup
return
elif ... ; then
some_command || (run_cleanup ; return 1)
else
...
fi
...
run_cleanup
}
Run Code Online (Sandbox Code Playgroud)
有没有办法避免run_cleanup在每个退出点重复(这很容易出错)?
解决方案是使用trap EXIT,它会注册一个清理操作,以便在函数完成时自动运行:
function foo {
trap run_cleanup EXIT
if ... ; then
...
return
elif ... ; then
some_command || return 1
else
...
fi
...
}
Run Code Online (Sandbox Code Playgroud)
trap ... EXIT请注意,在函数中使用是zsh特定的:
如果 sig 是
0orEXIT并且 trap 语句在函数体内执行,则命令 arg 将在函数完成后执行。...如果 sig 是0orEXIT并且 trap 语句不在函数体内执行,则命令 arg 在 shell 终止时执行。
bash命令中是trap ... RETURN.
如果sigspec为
EXIT(0),则在退出 shell 时执行命令 arg ...如果 sigspec为,RETURN则每次使用 或 内置函数执行的 shell 函数或脚本完成执行时,都会执行命令arg。.source