我想写函数abort
做一些工作人员然后中止调用函数。可能吗?
目标是模仿set -e
,但在功能级别 - 从函数返回而不是退出整个脚本。所以我需要把陷阱放在会杀死功能的ERR
上。
可能吗?
当程序退出非零时,您可以利用子壳允许它们“击中”。
将函数调用包装在括号中以在子shell中执行它。像这样的东西
#!/bin/bash
function abort {
set -e
exit 1
}
function f {
echo "Hello"
abort
echo "Will not be called"
}
(f)
echo "After f"
如果你希望你的f
总是“可以中止”,请将整个定义包装在括号中,然后每次调用时都不需要它们:
function f {(
echo "Hello"
abort
echo "Will not be called"
)}
听起来你只想在RETURN上找一个陷阱:
$ cat a.sh
#!/bin/bash
cleanup() {
echo 'foo invoked cleanup'
}
foo() {
trap cleanup return
test "$1" = fail && return 3 # instead of abort
trap : return # clear the trap to avoid calling cleanup
return 0
}
foo
echo foo returned $?
foo fail
echo foo returned $?
$ ./a.sh
foo returned 0
foo invoked cleanup
foo returned 3