Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have the following:

#!/bin/sh

n=('fred' 'bob')

f='n'
echo ${${f}[@]}

and I need that bottom line after substitutions to execute

echo ${n[@]}

any way to do this? I just get

test.sh: line 8: ${${f}}: bad substitution

on my end.

share|improve this question

2 Answers

up vote 9 down vote accepted

You can do variable indirection with arrays like this:

subst="$f[@]"
echo "${!subst}"

As soulmerge notes, you shouldn't use #!/bin/sh for this. I use #!/usr/bin/env bash as my shebang, which should work regardless of where Bash is in your path.

share|improve this answer
 
This worked beautifully! Thanks! –  Andy Dec 8 '11 at 17:57
3  
+1 Indirect expansion is far less of a bug magnet than eval. –  Gordon Davisson Dec 8 '11 at 23:24

You could eval the required line:

eval "echo \${${f}[@]}"

BTW: Your first line should be #!/bin/bash, you're using bash-specific stuff like arrays

share|improve this answer
 
+1 if I had any votes remaining today. Can you explain what eval does? –  jman Dec 8 '11 at 17:53
 
eval just evaluates the parameter string as a command. –  Andy Dec 8 '11 at 17:58
 
I do not understand why people keep downvoting without providing any feedback? –  soulmerge Dec 9 '11 at 0:21
 
I didn't downvote, but in general things like eval should be avoided in most languages if there is an alternative. They sometimes introduce subtle bugs or security risks. –  Michael Hoffman Dec 22 '11 at 21:28

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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