$ cat arrayloop
#! /usr/local/bin/bash
abc=(a b c)
def=(d e f)
ghi=(g h i)
array1=(abc def ghi)
cnt=0
total_Array=${#array1[*]}
no_loop_thru=${#abc[*]}
while [ $cnt -lt $total_Array ] ; do
srch_fld=${array1[$cnt]}
j=0
while [ $j -le $no_loop_thru ] ; do
eval var1=\${$srch_fld[$j]}
echo ${var1}
((j=j+1))
done
((cnt=cnt+1))
done
exit 0
$ ./arrayloop
a
b
c
d
e
f
g
h
i
$
The question remains same, but now the representation changed,
let
abc=(a b c)
def=(d e f)
ghi=(g h i)
array1=(abc def ghi)
now thing is in sub array i know the content or size, let here it is 3
so i want my o/p should come like
abc(1)=a
def(1)=d
ghi(1)=g
then
abc(2)=b
def(2)=e
ghi(2)=h
The first element of an array is 0, not 1.
var1=$srch_fld[$j]
echo "${srch_fld}(${j}) = ${!var1}"
will give you the correct indices. If you want to pretend that the first index is 1, you could use:
echo "${srch_fld}($((j+1))) = ${!var1}"
Modifying the code from Perderabo, how would you handle different-sized arrays in the inner while loop? For example, let's change the code to be:
$ cat arrayloop
#! /usr/local/bin/bash
abc=(a b c x y)
def=(d e f z)
ghi=(g h i)
array1=(abc def ghi)
cnt=0
total_Array=${#array1[*]}
while [ $cnt -lt $total_Array ] ; do
srch_fld=${array1[$cnt]}
j=0
while [ $j -le <????> ] ; do
eval var1=\${$srch_fld[$j]}
echo ${var1}
((j=j+1))
done
((cnt=cnt+1))
done
exit 0
$ ./arrayloop
a
b
c
x
y
d
e
f
z
g
h
i
$
We can't use the original no_loop_thru variable since the arrays are of varying length. I realize we need to get the length of srch_fld but I'm unable to get the syntax right ...