1

I would like to ask some help regarding variable variables in bash. I've read a few articles about it, but in my case I don't know how to do it. Let see my problem:

The array contains other arrays' names and I want to print the values of these arrays. In inner for I need variable variables.

#!/bin/bash
declare -a array=(dir1 dir2 dir3)
declare -a dir1=(1 2 3)
declare -a dir2=(a b c)
declare -a dir3=(9 8 7)

for elem1 in "${array[@]}"
do
  for elem2 in "${variableVariable[@]}"
  do
    echo "$elem1 : $elem2"
  done
done

The output should be something like this

dir1 : 1
dir1 : 2
dir1 : 3
dir2 : a
dir2 : b
dir2 : c
dir3 : 9
dir3 : 8
dir3 : 7
5
  • 2
    Don't use variable variables in this case. Use associative arrays. Commented May 2, 2013 at 5:52
  • 1
    possible duplicate of Lookup shell variables by name, indirectly Commented May 2, 2013 at 6:01
  • Thanks Guys! The links are useful! Commented May 2, 2013 at 7:29
  • @tripleee It's similar to that question, but there's some extra work you have to do to deal with [@] when indirecting. It took me a while to figure it out. Commented May 2, 2013 at 7:34
  • Mine problem is the how to deal with [@] part of the script. Can you help me? Commented May 3, 2013 at 18:02

2 Answers 2

7

This can be done using bash's indirect variable feature.

for elem1 in "${array[@]}"
do
  elems=$elem1'[@]'
  for elem2 in "${!elems}"
  do
    echo "$elem1 : $elem2"
  done
done

Note that this is a bash extension, it's not portable to other shells.

Sign up to request clarification or add additional context in comments.

1 Comment

I'll take a look at it. I would like to run my script in git shell on windows.
0

Finally, I found the solution. I had to use eval because I was not able to deal with the other syntax, I mean the composition of the ${!variable} and the ${variable[@]}.

#!/bin/bash
declare -a array=(dir1 dir2 dir3)
declare -a dir1=(1 2 3)
declare -a dir2=(a b c)
declare -a dir3=(9 8 7)

for elem1 in "${array[@]}"
do
  for elem2 in `eval echo \$\{$elem1\[@\]\}"`
  do
    echo "$elem1 : $elem2"
  done
done

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.