2

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.

рüффп
  • 1,707
darkspine
  • 133

2 Answers2

5

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.

heemayl
  • 56,300
2

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\$ 
Thomas Dickey
  • 76,765
  • 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). – darkspine Mar 16 '16 at 10:31
  • Thanks, it works well in pure sh too, useful trick on small bash-less docker images! – Mariusz Oct 12 '18 at 06:49