LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   bash - loop over variable array names (http://www.linuxquestions.org/questions/programming-9/bash-loop-over-variable-array-names-705702/)

talanis 02-18-2009 03:59 PM

bash - loop over variable array names
 
Hello,

i have a little problem concerning variable variable names in bash.
I am doing a loop to fill multiple arrays.

if i want to output the arrays, i can, however, do it only one by one; not in another loop.
Quote:

#!/bin/bash

for (( n=0; n<5; n++ )); # create 5 arrays
do
let array$n[0]="432859"

done


echo ${array0[*]} # arrays 0 to 4 can be easily displayed.
echo ${array1[*]} # but i want it as a loop (necessary in mightier programs)
echo ${array2[*]} # and so on...

#this loop does not work.
#line 16: ${array$y[*]}: bad substitution
for (( y=0; y<$n; y++ ));
do
echo ${array$y[*]} |sed s/"533862"/" "/g
done
Since i need to loop over the output, so i really only get the lines that where filled, any help is really appreciated!

Hko 02-18-2009 06:35 PM

Code:

#!/bin/bash

array0=(Hello Hallo Hola Aloha)
array1=(one two three four)
array2=(1 2 3 4)

echo "Printing them the normal way:"
echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
echo ${array0[*]}
echo ${array1[*]}
echo ${array2[*]}
echo

echo "Printing them from a loop:"
echo "~~~~~~~~~~~~~~~~~~~~~~~~~~"
for (( y=0; y<3; y++ )); do
    echo $(eval echo \${array$y[*]})
done


talanis 02-19-2009 11:09 AM

Thanks man!
It works like a charm. Perfect ^^


All times are GMT -5. The time now is 11:31 PM.