Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parent function argument length in bash?

Tags:

bash

shell

You're able to access the parent function name with ${FUNCNAME[1]} (In BASH, is it possible to get the function name in function body?). Is there a way to also access the parent function argument length (arity)?

So instead of this:

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

You could do something like this:

get() {
  assert_arity 2
}

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

Is that possible?

like image 471
Lance Avatar asked Jul 16 '26 17:07

Lance


2 Answers

It is possible:

shopt -s extdebug

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

BASH_ARGC is set only in extdebug mode. If it is, it is an array of the number of arguments of the whole call stack, with the current frame at index 0.

like image 77
Renaud Pacalet Avatar answered Jul 19 '26 10:07

Renaud Pacalet


If all you want is a cleaner code you can pass the actual arguments to the assert_arity() function like this:

get() {
  assert_arity 2 "$@"
}

assert_arity() {
  local arity=$(( $# - 1 ))
  local value=$1
  [ "${arity}" != "${value}" ] && exit 1
}
like image 45
vlp Avatar answered Jul 19 '26 10:07

vlp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!