Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill array passed as argument in bash function

I need to fill an array inside a function, passing it as an argument and NOT using a global variable (the function will be called here and there with different arrays).

I've read this discussion bash how to pass array as an argument to a function and used the pass-by-name solution, that ALMOST do the trick.

Here is my code

#!/bin/bash

function fillArray {
  arrayName=$1[@]
  array=("${!arrayName}")
  for i in 0 1 2 3
  do
    array+=("new item $i")
  done

  echo "Tot items in function: ${#array[@]}"
  for item in "${array[@]}"
  do
    echo $item
  done
  echo
}

myArray=("my item 0" "my item 1")

fillArray myArray

echo "Tot items in main: ${#myArray[@]}"
for item in "${myArray[@]}"
do
  echo $item
done

Here is the output

Tot items in function: 6
my item 0
my item 1
new item 0
new item 1
new item 2
new item 3

Tot items in main: 2
my item 0
my item 1

So, the function correctly use the array passed as parameter (first two items are the one added in main declaration), and append the new items to the array. After the function call, in main, the added items are lost.

What am I missing? Probably some pass-by-reference/pass-by-copy things...

Thanks!

like image 645
il_mix Avatar asked Apr 09 '26 20:04

il_mix


1 Answers

For future reference, this becomes trivial with named references in bash 4.3:

function fillArray {
  declare -n arrayName=$1

  for i in 0 1 2 3
  do
    arrayName+=("new item $i")
  done

  echo "Tot items in function: ${#arrayName[@]}"
  for item in "${arrayName[@]}"
  do
    echo $item
  done
  echo
}
like image 112
chepner Avatar answered Apr 11 '26 12:04

chepner