我在脚本中一直使用像这样的简单bash序言:
#!/bin/bash
set -e
结合模块化/使用功能,这今天困扰了我。
所以,说我有一个类似的功能
foo() {
#edit: some error happens that make me want to exit the function and signal that to the caller
return 2
}
理想情况下,我希望能够使用多个小文件,将它们的功能包含在其他文件中,然后像
set +e
foo
rc=$?
set -e
。这恰好适用于两层例程。但是,如果foo也这样调用子例程,则返回之前的最后一个设置将是set -e
,这将使脚本在返回时退出-我无法在调用函数中覆盖此函数。所以,我要做的是
foo() {
#calling bar() in a shielded way like above
#..
set +e
return 2
}
我发现这很违反直觉(也不是我想要的)-如果在某些情况下我想使用该函数而不屏蔽故障,而在其他情况下我想处理清理该怎么办?)什么是最好的处理方式? ?顺便说一句。我正在OSX上执行此操作,尚未测试Linux上的这种行为是否有所不同。
Shell函数实际上并没有“返回值”,只是退出代码。
您可以将其添加&& :
到调用方,这会使命令“经过测试”,并且不会退出该命令:
foo() {
echo 'x'
return 42
}
out=$(foo && :)
echo $out
该:
是“空指令”(即它没有做任何事情)。在这种情况下,它甚至不会被执行,因为它仅在foo
返回0时才运行(不是)。
输出:
x
可以说这有点丑陋,但是话又说回来,所有的shell脚本都可以说有点丑陋;-)
引用sh(1)
FreeBSD,它比bash的手册页更好地解释了这一点:
-e errexit
Exit immediately if any untested command fails in non-interactive
mode. The exit status of a command is considered to be explicitly
tested if the command is part of the list used to control an if,
elif, while, or until; if the command is the left hand operand of
an “&&” or “||” operator; or if the command is a pipeline preceded
by the ! operator. If a shell function is executed and its exit
status is explicitly tested, all commands of the function are con‐
sidered to be tested as well.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句