0

我想将一个数组作为参数传递给一个函数并向数组中添加一个新元素。然后将数组传递给另一个函数并打印其内容。(所有这些都在 Bash 中。)

syntax error near unexpected token `"$2"'
`        $1+=("$2")'

这就是我得到的全部,可能是因为在为变量赋值$时无法使用。我不知道如何解决这个问题。你能帮助我吗?

这是我的方法:

#/bin/bash

add_element()
{
    $1+=("$2")
}

print_array()
{
    for i in "${$1[@]}"
    do
        echo "$i"
    done
}

declare -a ARRAY

add_element ARRAY "a"
add_element ARRAY "b"
add_element ARRAY "1,2"
add_element ARRAY "d"

print_array ARRAY
4

1 回答 1

1

Here's a possibility, using indirect expansion.

#/bin/bash

add_element()
{
    local a="$1[@]"
    a=( "${!a}" )
    printf -v "$1[${#a[@]}]" "%s" "$2"
}

print_array()
{
    local a="$1[@]"
    printf '%s\n' "${!a}"
}

declare -a array

add_element array "a"
add_element array "b"
add_element array "1,2"
add_element array "d"

print_array array

Comments:

  • It's really ugly. I don't know why you want that. Please realize that bash isn't designed to do things like these. Maybe you want to use php or perl or java or something else instead.
  • Don't use upper-case variable names in bash. It's considered very bad bash practice. It's ugly. It's terrible, especially when it potentially clashes with other variables, and it could be the case here if someone uses the mapfile builtin (which by default stores in an array named ARRAY).
  • Please consider using something different to achieve what you're trying to. Really, you don't need functions like these in bash.
于 2012-12-22T09:54:47.690 回答