0

I'd like to pass an array as argument to a function and add a new element to the array. Then pass the array to another function and print its contents. (All this in Bash.)

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

This is all I get, probably because when assigning a value to a variable $ can't be used. I don't know how to solve this problem. Can you help me?

Here is my approach:

#/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
3
  • 2
    so what is the question if I may ask Commented Dec 22, 2012 at 9:31
  • @Satya Actual question added. Commented Dec 22, 2012 at 9:38
  • If you change the line in add_element to something like this: eval $a+='('$*')' ; then you should be golden. Commented Mar 21, 2013 at 12:02

1 Answer 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.
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer. However I'm trying to test/push the limits of Bash. And thanks for the advice regarding variable names.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.