0

For example in this simple script

    #!/bin/bash
    
    declare -a MYARRAY1
    declare -a MYARRAY2
    
    function updatearray {
    ARRAY=$1
    VALUE=$2
    
    $ARRAY+=$VALUE
    
    }

    updatearray MYARRAY1  "yyyy "
    updatearray MYARRAY2  "bbbb "
    
    echo "${MYARRAY1[@]}"
    echo "${MYARRAY2[@]}"
    
    exit 0

Just results in "line 10: MYARRAY1+=yyyy: command not found" rather than updating the array. This is actually for a more complex bash script I'm working on that has more arrays I want to update, so I'm hoping to avoid 'case' statements which would mean a big function body

2
  • You need bash 4.3 or later; the feature you want is called namerefs Commented Aug 3, 2021 at 14:51
  • By the way, it's better form to use POSIX function declarations -- updatearray() { with no function. See wiki.bash-hackers.org/scripting/obsolete Commented Aug 3, 2021 at 14:51

1 Answer 1

1

You can use namerefs, but take care:

updatearray () {
    declare -n a=$1
    a+=$2
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.