【问题标题】:how to access to array element when passed to function传递给函数时如何访问数组元素
【发布时间】:2014-03-06 21:13:57
【问题描述】:

当我们在 bash 脚本中将数组传递给函数时,我们如何访问元素?例如我有这个代码:

check_corrects() {
    local inp=$1[@]
    echo # i want to echo inp[0]
}
a=(1 2 3)
check_corrects a 

我怎样才能回显inp[0]

【问题讨论】:

  • check_corrects a 没有将数组或其任何部分传递给check_corrects。它正在传递单个 1 字符字符串“a”...

标签: bash function


【解决方案1】:

您不能将数组作为参数传递给 shell 函数。参数只是编号的参数。您可以使数组成为这些参数:

testa() { echo "$#"; }
a=(1 2 3)
testa "${a[@]}"
3

testa $a 会回显1,因为它只会将“a”的第一个元素传递给testa。

但这意味着,在你的情况下,如果你只是直接回显数组扩展,你会得到第一个参数,这就是你想要的。

echo "$1"

【讨论】:

    【解决方案2】:

    警告:前方极度丑陋。不适合胆小的人:

    check_corrects() {
        local arrayref="$1[@]"
        local array=("${!arrayref}")   # gulp, indirect variable
        local idx=$2
        echo "${array[$idx]}"
    }
    

    现在,让我们测试一下

    a=( 1 2 "foo bar" 3)
    check_corrects a 2      # ==> "foo bar"
    

    呼。

    不适用于关联数组:"${ary[@]}" 只返回值,不返回键。 此外,不适用于键不连续的数字数组。

    【讨论】:

      【解决方案3】:

      只是为了阐述小次郎的回答,说的很对……

      当我想传递整个数组时,我经常这样做:

      foo() {
        local a=( "$@" )
        ...
      }
      
      a=(1 2 3)
      foo "${a[@]}"
      

      这基本上将值重建回foo() 内的数组。请注意,如果单个数组元素的值可能包含空格,则引号至关重要。例如:

      foo() {
        local a=( "$@" )
        echo "foo: Number of elements in a: ${#a[@]}"
      }
      
      bar() {
        local a=( $@ ) # wrong
        echo "bar: Number of elements in a: ${#a[@]}"
      }
      
      a=(1 2 3 4)
      foo "${a[@]}"  # Reports 4 elements, as expected
      bar "${a[@]}"  # Also reports 4 elements, so where's the problem?
      
      a=("1 2" 3 "4 5 6")
      foo "${a[@]}"  # Reports 3 elements, as expected
      bar "${a[@]}"  # Reports 6 elements. Oops!
      

      编辑:虽然我的示例没有显示,但调用方的引号也很重要。也就是说,如果您执行foo ${a[@]},您将遇到与上述示例中bar 相同的问题。底线是如果您的数组元素将包含空格,则需要使用引号。更详细的解释见What is the difference between $@ and $* in shell scripts?

      【讨论】:

        猜你喜欢
        • 2023-02-25
        • 1970-01-01
        • 1970-01-01
        • 2012-05-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-12
        • 2016-09-26
        相关资源
        最近更新 更多