I know you can create an indirect parameter expansion to an array like so:
var1=\"target\"
var2=\"arrayname\"
targetarrayname=( \"one\" \"two\" \"three\" )
b
It avoids substantial security bugs to run all values through printf %q
to ensure that they're safely escaped before substituting them into eval
content.
#!/bin/bash
appendToArray() {
local _targetArrayName _argumentData _cmd
_targetArrayName=$1; shift || return
printf -v _argumentData '%q ' "$@"
printf -v _cmd '%q+=( %s )' "$_targetArrayName" "$_argumentData"
eval "$_cmd"
}
target=( "first item" "second item" )
appendToArray target "third item" "fourth item"
declare -p target
...correctly emits as output:
declare -a target=([0]="first item" [1]="second item" [2]="third item" [3]="fourth item")
#!/bin/bash
appendToArray() {
declare -n _targetArray=$1; shift
_targetArray+=( "$@" )
}
target=( "first item" "second item" )
appendToArray target "third item" "fourth item"
declare -p target
...has identical output, with much less (and much simpler) code.