Is the number of arguments that a bash function can accept limited?
Passing arguments before runningWe can pass parameters just after the name of the script while running the bash interpreter command. You can pass parameters or arguments to the file.
Bash Function ArgumentsTo pass arguments to a function, add the parameters after the function call separated by spaces.
To pass multiple arguments to a shell script you simply add them to the command line: # somescript arg1 arg2 arg3 arg4 arg5 … To pass multiple arguments to a shell script you simply add them to the command line: # somescript arg1 arg2 arg3 arg4 arg5 …
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}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With