2

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.

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

I have another question on the same tolpic. Maybe you can help me there as well: stackoverflow.com/questions/29015565/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.