2

I essentially have a for loop where the variable i that I am iterating with will take on each letter of the alphabet, for example. I want to use each value of i to create an array called "$i"array (for instance aarray, barray, carray, darray, etc) or even just called "$i" (so the arrays could be called a, b, c, d, etc.).

What kind of syntax could I use to make this happen?

I have tried:

for i in ${alphabet[@]}; do
    "$i"array[0]=0
done

and once I have my group of arrays, could I iterate through them by doing

for i in ${alphabet[@]}; do
    "$i"array[0]=1
done
  • Ouch, please don't. Use an associative array – glenn jackman Jan 16 '15 at 12:29
2

Can I offer other way (via associative array) to do your task? It seems more clever and acceptable:

declare -A array
for i in ${alphabet[@]}; do
  array[$i]=0
  # or array[${i}0]=0 if you need 
done

So you can iterate through it by for i in ${!array[@]} or same wayfor i in ${alphabet[@]}

  • Or use a pseudo 2-dimensional array: array[$i,0]=1 – glenn jackman Jan 16 '15 at 12:28
  • @glennjackman By the way is there some advantage to use "pseudo 2-dimensional" array instead of ordinary associative one? – Costas Jan 16 '15 at 12:34
  • From the question, sounds like he wants an array-of-arrays. This can be implemented with my suggestion – glenn jackman Jan 16 '15 at 14:28
  • @glennjackman Sure. But is there difference between ${i},0 and ${i}0 or $i 0? How I understand any of variants just treated as string no matter with or without separator(s) inside? – Costas Jan 16 '15 at 14:44
1

You can use eval builtin to evaluate the variable name. An example that illustrates the point:

i="a"
eval ${i}lphabet="abcde"
echo $alphabet

However, retrieving the value from ${i}lphabet requires another trick. You have to use the value of a variable as a variable name (essentially a pointer). The syntax would be:

#declare a variable that names the other variable:
pointer=${i}lphabet
#dereference the name with the ! syntax:
echo ${!pointer}

Applied to your case:

for i in ${alphabet[@]}; do
    pointer="$i"array
    eval ${pointer}[0]=0
done

However, this is a bad design... you should find a more conventional way of handling this.

1

You will have to use eval to use the contents of variables as variable names:

for i in ${alphabet[@]}; do
    eval "$i[0]=1"
done

eval takes its arguments and evaluates it in the context of the shell, i.e. not as a separate shell, attempts to do this without eval will result in separate shells being started and hence the variables set will not be available in the first shell.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.