在bash中获取父函数参数长度?

时间:2015-09-12 17:05:44

标签: bash shell

您可以使用${FUNCNAME[1]}In BASH, is it possible to get the function name in function body?)访问父函数名称。有没有办法同时访问父函数参数长度(arity)?

所以不要这样:

get() {
  [ "$#" != 2 ] && exit 1
}

你可以这样做:

get() {
  assert_arity 2
}

assert_arity() {
  local arity=${parent_function_arity}
  local value=$1
  [ "${arity}" != "${value}" ] && exit 1
}

这可能吗?

3 个答案:

答案 0 :(得分:2)

有可能:

shopt -s extdebug

assert_arity() {
    local arity=${BASH_ARGC[1]}
    local value=$1
    [ "${arity}" != "${value}" ] && echo "nope"
}

BASH_ARGC仅在extdebug模式下设置。如果是,则它是整个调用堆栈的参数个数的数组,当前帧在索引0处。

答案 1 :(得分:2)

如果您想要的只是一个更干净的代码,您可以将实际参数传递给assert_arity()函数,如下所示:

get() {
  assert_arity 2 "$@"
}

assert_arity() {
  local arity=$(( $# - 1 ))
  local value=$1
  [ "${arity}" != "${value}" ] && exit 1
}

答案 2 :(得分:0)

如果设置extdebug shell选项,则当前调用堆栈的arities存储在数组BASH_ARGC中。

shopt -s extdebug

get () {
  assert_arty 2
}

assert_arity () {
  local arity=${BASH_ARGC[1]}  # 0 is us, 1 is the parent
  local value=$1
  (( arity != value )) && exit 1
}