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

2 Answers 2

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.

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\$ 
2
  • 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, 2016 at 10:31
  • Thanks, it works well in pure sh too, useful trick on small bash-less docker images!
    – Mariusz
    Oct 12, 2018 at 6:49

Not the answer you're looking for? Browse other questions tagged .