Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This question already has an answer here:

Suppose i have the following:

foo1=abc
i=1
a="FOO${i}"
echo ${${a}}
echo ${`echo $a`} # I also tried that

I am getting the error bash: ${${a}}: bad substitution.

Thanks

share|improve this question

marked as duplicate by don_crissti, maxschlepzig, Archemar, Jeff Schaller, Stephen Kitt 2 days ago

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1  
mywiki.wooledge.org/BashFAQ/006 and look for indirect variable reference. – val0x00ff 2 days ago
up vote 3 down vote accepted

You can use parameter indirection ${!parameter} i.e. in your case ${!a}:

$ foo1=abc
$ i=1
$ a="foo${i}"
$ echo "${!a}"
abc

From "Parameter Expansion" section of man bash:

${parameter}

.......

If the first character of parameter is an exclamation point (!), it introduces a level of variable indirection. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself.

share|improve this answer

You can use eval for this (and it would work with any POSIX shell, including bash):

eval 'echo $'$a

To illustrate:

#!/bin/bash -i

PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
PS2='Second prompt \u@\h:\w\$ '
PS3='Third prompt \u@\h:\w\$ '
echo "PS1:$PS1"
for n in 3 2 1
do
        eval 'PS0="$PS'$n'"'
        echo "$PS0"
done

produces (call the script "foo"):

$ ./foo
PS1:${debian_chroot:+($debian_chroot)}\u@\h:\w\$ 
Third prompt \u@\h:\w\$ 
Second prompt \u@\h:\w\$ 
${debian_chroot:+($debian_chroot)}\u@\h:\w\$ 
share|improve this answer
    
I originally found this solution and was unable to make it work with my script (which had to do with $PS1 setting. It bsaically had to set PS1 to PS11, PS12, etc depending on input (1,2,etc). – Srathi00 2 days ago

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