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!