【发布时间】:2018-09-22 06:36:17
【问题描述】:
这个问题是以前提出的问题的变体,例如How to return an error from a sourced bash script.
然而,我想要的是源函数 X 调用第二个函数 Y,然后将函数 Y 的返回码返回给调用者。
目前,我的脚本使用这种模式工作:
function_x() {
function_y || return $?
}
function_y() {
return 1
}
然而,在实践中,这会导致我的代码中出现大量返回语句。
假设函数 Y 实际上是一个使用函数。然后我得到了丑陋的代码,不是很干,像这样:
_usage() {
echo "Usage: $0 [-h] OPTIONS"
return 0
}
function_a() {
[ "$1" == "-h" ] && _usage && return 1
some_other_condition && _usage && return 1
yet_another_condition && _usage && return 1
...
}
(我的实际代码是here。)
一般来说,函数 X 调用第二个函数 Y,然后将 Y 的返回码返回给调用者,有没有一种简洁的方法?
【问题讨论】:
标签: bash