Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending to an array w/ its name passed as a bash function parameter

Tags:

bash

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?

like image 322
Mouin Avatar asked Aug 16 '26 13:08

Mouin


2 Answers

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")
}
like image 137
Benjamin W. Avatar answered Aug 19 '26 02:08

Benjamin W.


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?

like image 45
Charles Duffy Avatar answered Aug 19 '26 03:08

Charles Duffy