3

Hi I am having an array and want to add strings that contain spaces. How can this be done? the following example code shows what I want to do:

#!/bin/bash

# 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
#declare -p AARRAY
iMax=${#AARRAY[@]}
echo "HERE ARRAYCOUNT: $iMax ITEMS in ARRAY"

ShowArray1 "AARRAY"
sParam="1st Item"
AARRAY+=($sParam)

ShowArray1 "AARRAY"

Problem is that the Item "1st Item" is added as two elements into the array. Output:

Showing content of array
ARRAYCOUNT: 2
ITEM: 1st
ITEM: Item

1 Answer 1

9

Double quote the variable to prevent the expansion:

AARRAY+=("$sParam")
Sign up to request clarification or add additional context in comments.

Comments

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.