hy-soft
hy-soft

Reputation: 173

Bash passing an array to a function inserts empty element

I am passing an empty array to a function and within the function the array has one element but the element is empty.

#!/bin/bash
#ytest
#==============================================================
function ShowArray
{
echo "in ShowArray"

AlocalArray=("${!1}")

#alternatively you could do it like that
#echo "${AlocalArray[@]}"                      #DEBUG

echo "Showing content of array"

local iMax

   iMax=${#AlocalArray[*]}

   echo "ARRAYCOUNT: $iMax"
   for ((iItem=0; iItem < iMax ; iItem++))
   do
      echo "ITEM: ${AlocalArray[$iItem]}"
   done
}


declare -a AARRAY
echo "${AARRAY[@]}"                      #DEBUG
iMax=${#AARRAY[*]}

echo "HERE ARRAYCOUNT: $iMax ITEMS in ARRAY"
ShowArray "$AARRAY"

From the body of the script I get:

HERE ARRAYCOUNT: 0 ITEMS in ARRAY

From within the function I get:

in ShowArray
Showing content of array
ARRAYCOUNT: 1
ITEM: 

What's wrong with my code? Thanks in advance.

Disclaimer: this demo script does nothing useful and serves only the purpose to demonstrate the misbehaviour.

Upvotes: 2

Views: 90

Answers (1)

anubhava
anubhava

Reputation: 785406

That is not correct way to pass arrays in BASH and your ShowArray function is not accessing the same array created outside.

Here is how you can pass array in BASH (old and new versions)

# works for older BASH version 3 also
ShowArray() {
   echo "in ShowArray -----------------------"
   AlocalArray=("${!1}")
   declare -p AlocalArray
   echo "Showing content of array"

   local iMax=${#AlocalArray[@]}    
   echo "ARRAYCOUNT: $iMax"
   for ((iItem=0; iItem < iMax ; iItem++)); do
      echo "ITEM: ${AlocalArray[$iItem]}"
   done
}

# works on BASH versions >4
ShowArray1() {
   echo "in ShowArray1 -----------------------"
   declare -n AlocalArray="$1"
   declare -p AlocalArray
   echo "Showing content of array"

   local iMax=${#AlocalArray[@]}    
   echo "ARRAYCOUNT: $iMax"
   for ((iItem=0; iItem < iMax ; iItem++)); do
      echo "ITEM: ${AlocalArray[$iItem]}"
   done
}

declare -a AARRAY=(foo bar)
declare -p AARRAY
iMax=${#AARRAY[@]}
echo "HERE ARRAYCOUNT: $iMax ITEMS in ARRAY"
ShowArray "AARRAY[@]"
ShowArray1 "AARRAY"

Output:

declare -a AARRAY='([0]="foo" [1]="bar")'
HERE ARRAYCOUNT: 2 ITEMS in ARRAY
in ShowArray -----------------------
declare -a AlocalArray='([0]="foo" [1]="bar")'
Showing content of array
ARRAYCOUNT: 2
ITEM: foo
ITEM: bar
in ShowArray1 -----------------------
declare -n AlocalArray="AARRAY"
Showing content of array
ARRAYCOUNT: 2
ITEM: foo
ITEM: bar

Upvotes: 2

Related Questions