我可以向 bash 函数传递多少个参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3986099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 22:48:08  来源:igfitidea点击:

How many arguments can I pass to a bash function?

bash

提问by zedoo

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

bash 函数可以接受的参数数量是否有限?

采纳答案by unwind

The bash manualsays:

bash的手册说:

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.

我相信这适用,因为函数参数以数组的形式呈现。

回答by Paused until further notice.

To access arguments in a function, you can iterate over them:

要访问函数中的参数,您可以遍历它们:

foo () {
    for arg    # "in $@" is implied
    do
        echo $arg
    done
}

or

或者

bar () {
    while [  ]
    do
        echo 
        shift
    done
}

or to access specific arguments:

或访问特定参数:

baz () {
    # for arguments above  you have to use curly braces
    echo    ${121375}
}

回答by Michael Kropat

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.

如您所见,它大于内核 ARG_MAX limit,这是有道理的,因为 Bash 不会调用execve(2)来调用 Bash 定义的函数。

I get mallocfailures 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.

malloc如果我尝试{1..NUM}在 2^32 范围内执行 Bash 序列扩展 ( ),我会失败,因此某处存在硬限制(可能因您的机器而异),但是一旦超过 2^20 个参数,Bash 就会变得很慢,那在达到硬限制之前,您将很早就达到性能限制。