如何在bash中使用多个出口陷阱?假设我想在出口代码1上运行-1出口,在出口代码2上运行
function on-exit1 {
echo "do stuff here if code had exit status 1"
}
function on-exit2 {
echo "do stuff here if code had exit status 2"
}
.....
trap on-exit1 EXIT # <--- what do i do here to specify the exit code to trap
trap on-exit2 EXIT # <--- what do i do here to specify the exit code to trap
.....
some bashing up in here
blah...blah
exit 1 # do on-exit1
else blah blah
exit 2 # do on-exit2
else blah blah
exit N # do on-exitNth发布于 2016-12-06 10:12:45
类似于以下代码示例的代码应该可以工作:
exit_check () {
# bash variable $? contains the last function exit code
# will run the function on_exit1 if status exit is 1, on_exit2 if status exit is 2, ...
on_exit$?
}
trap exit_check EXIT 发布于 2016-12-06 10:02:05
如果您真的想使用陷阱,请尝试如下:
#!/usr/bin/env bash
function finish {
echo "exitcode: $?"
}
trap finish EXIT
read -n 1 -s exitcode
exit $exitcode但正如@123建议的那样,你只需调用退出函数,就不需要在这里“滥用”陷阱。
下次试着提供一个有用的例子;)。
https://stackoverflow.com/questions/40992236
复制相似问题