Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many arguments can I pass to a bash function?

Tags:

bash

Is the number of arguments that a bash function can accept limited?

like image 249
zedoo Avatar asked Oct 21 '10 09:10

zedoo


People also ask

Can you pass arguments to a bash script?

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.

Can bash function take arguments?

Bash Function ArgumentsTo pass arguments to a function, add the parameters after the function call separated by spaces.

How do I pass multiple arguments to a shell script?

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 …


2 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}
}
like image 167
Dennis Williamson Avatar answered Oct 22 '22 14:10

Dennis Williamson


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.

like image 21
Michael Kropat Avatar answered Oct 22 '22 15:10

Michael Kropat