Loop through array of arrays of string with spaces

Hi

I'm trying to loop through an array that contains other arrays and these arrays consist of strings with spaces. The problem is that I can't seem to preserve the spacing in the string. The string with spaces are either divided into multiple items if I change IFS to \n or all the elements of the array are seen as 1 item if I leave IFS unchanged here's some sample code:

#! /bin/sh
low1=("AA  QQ" "BB  LL")
low2=("CC" "DD")
low3=("EE" "FF")
high=(low1 low2 low3)

for high_item in ${high[@]}
do
   eval arrayz=\${$high_item[@]}
   #IFS=$'\n'
   for item in $arrayz
   do
      echo $item
   done
done

Output:
AA
QQ
BB
LL
CC
DD
EE
FF

As you can see the elements "AA QQ" and "BB LL" have been split.

If I uncomment the line that sets IFS to \n I get the following:

AA QQ BB LL
CC DD
EE FF

Now "AA QQ" and "BB LL" are concatenated!

Is there anyway I can preserve these elements just as they original are...I need the output to look like that:

AA QQ
BB LL
CC DD
EE FF

Any ideas?

Try this..:slight_smile:

#! /bin/sh
low1=("AA  QQ" "BB  LL")
low2=("CC" "DD")
low3=("EE" "FF")
high=(low1 low2 low3)

for high_item in ${high[@]}
do
   eval arrayz=\${$high_item[@]}
   #IFS=$'\n'
   for item in "$arrayz"
   do
      echo $item
   done
done

hi pamu

tried adding quotes but the strings remain concatenated

AA QQ BB LL
CC DD
EE FF

Like this?

#! /bin/sh
low1=("AA  QQ" "BB  LL")
low2=("CC" "DD")
low3=("EE" "FF")
high=(low1 low2 low3)

for high_item in ${high[@]}
do
   eval 'for i in "${'$high_item'[@]}";do echo "$i";done'
done

producing

AA  QQ
BB  LL
CC
DD
EE
FF

Yes. I would simplify the approach. If you're going to hardcode the names of the arrays, then you lose nothing by hardcoding the expansion of those arrays.

low1=("AA  QQ" "BB  LL")
low2=("CC" "DD")
low3=("EE" "FF")
high=("${low1[@]}" "${low2[@]}" "${low3[@]}")

for i in "${high[@]}"
do
      echo "$i"
done

A couple other suggestions:

  1. On many systems, /bin/sh does not support arrays. Nor does it support that $'\n' string syntax. If a script depends on bash (or other non-/bin/sh shell), it's a good idea to state it explicitly at the start of the script. It's preferable to fail loudly (with an interpreter not found message) than to chug along with syntax errors (or worse, silent errors) while using the wrong interpreter.
  2. echo "$data" can be problematic if $data ever resembles a command option. Better to use printf '%s\n' "$data" .

Regards,
Alister