1

In Linux Bash,

a1=web
a2=app
for counter in 1 2
do
a=a$counter
echo $[$a]
done

So,

$[$a]

How would it echo web & app?

Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60
Louis.C
  • 25
  • 3
  • 1
    You can use echo `${!a}` This is introduces a level of [variable indirection](http://stackoverflow.com/a/1921337/5894196). – logan rakai Dec 10 '16 at 03:48
  • If your variables are all `a*` and nothing else matches, then you can simplify your code to `for each in ${!a*}; do echo ${!each}; done`. – alvits Dec 10 '16 at 03:54
  • Possible duplicate of [Bash dynamic variable names](http://stackoverflow.com/questions/16553089/bash-dynamic-variable-names) – Ruslan Osmanov Dec 10 '16 at 03:59

1 Answers1

3

What you are trying now works for integer-valued variables, because arithmetic expansion performs recursive expansion of strings as parameters until an integer value is found. For instance:

$ web=1
$ a=web
$ echo $[a]
1
$ echo $((a))
1

$[...] is just an obsolete form of arithmetic expression that predates the POSIX standard $((...)).

However, you are looking for simple indirect expansion, where the value of a parameter is used as the name of another parameter with an arbitrary value, rather than continuously expanding until an integer is found. In this case, use the ${!...} form of parameter expansion.

$ a=web
$ a1=a
$ echo $a1
a
$ echo ${!a1}
web
mklement0
  • 382,024
  • 64
  • 607
  • 775
chepner
  • 497,756
  • 71
  • 530
  • 681