I am writing a function that adds an element to the end of an array passed in parameter:
#@function add_elem_to_array: add an element to an array
#in:
#1 name of the array
#2 element to add
add_elem_to_array()
{
elem=$1
array=$2
index=${#array[@]} #get the index where to insert
eval "$array[$index]=$elem" #!!!! The problem is here
}
Could you please help me to figure out the solution?
I wouldn't use a function for this:
array+=("$elem")
appends an element.
If you really want to use a function and you have Bash 4.3 or newer, you can use a nameref:
add_elem_to_array () {
local elem=$1
local -n arr=$2
arr+=("$elem")
}
Assuming bash 4.3 or newer, thus having namevars (declare -n / local -n):
add_elem_to_array() {
local elem=$1 array_name=$2
local -n array=$array_name
array+=( "$elem" )
}
Supporting bash 3.x (particularly including 3.2, the oldest version in widespread use as of this writing):
add_elem_to_array() {
local elem=$1 array_name=$2
local cmd
printf -v cmd '%q+=( %q )' "$array_name" "$elem"
eval "$cmd"
}
That said -- given array+=( "$value" ) as an available syntax, there's little need for a function for the purpose, is there?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With