您可以使用${FUNCNAME[1]}(在 BASH 中,是否可以在函数体中获取函数名称?)来访问父函数名称。有没有办法也访问父函数参数长度(arity)?
所以代替这个:
get() {
[ "$#" != 2 ] && exit 1
}
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
get() {
assert_arity 2
}
assert_arity() {
local arity=${parent_function_arity}
local value=$1
[ "${arity}" != "${value}" ] && exit 1
}
Run Code Online (Sandbox Code Playgroud)
那可能吗?
有可能的:
shopt -s extdebug
assert_arity() {
local arity=${BASH_ARGC[1]}
local value=$1
[ "${arity}" != "${value}" ] && echo "nope"
}
Run Code Online (Sandbox Code Playgroud)
BASH_ARGC仅在模式下设置extdebug。如果是,则它是整个调用堆栈的参数数量的数组,当前帧的索引为 0。