Is the number of arguments that a bash function can accept limited?
3 Answers
To access arguments in a function, you can iterate over them:
foo () {
for arg # "in $@" is implied
do
echo $arg
done
}
or
bar () {
while [ $1 ]
do
echo $1
shift
done
}
or to access specific arguments:
baz () {
# for arguments above $9 you have to use curly braces
echo $1 $9 ${10} ${121375}
}
-
This should be the accepted answer! The last example answers why 99.9999% of people arrive at this question: because Bash does not accept referencing array variables above 9, except when using curly braces! Commented Apr 4 at 8:56
The number is fairly large:
$ display_last_arg() { echo "${@: -1}"; }
$ getconf ARG_MAX
262144
$ display_last_arg {1..262145}
262145
$ echo $(( 2**18 )) $(( 2**20 ))
262144 1048576
$ display_last_arg {1..1048576}
1048576
As you can see, it's larger than the kernel ARG_MAX limit, which makes sense since Bash does not call execve(2) to invoke Bash-defined functions.
I get malloc failures if I try to perform Bash sequence expansion ({1..NUM}) in the 2^32 range, so there is a hard limit somewhere (might vary on your machine), but Bash is so slow once you get above 2^20 arguments, that you will hit a performance limit well before you hit a hard limit.
The bash manual says:
There is no maximum limit on the size of an array, nor any requirement that members be indexed or assigned contiguously.
I believe this applies, since function arguments are presented as an array.