Louis.C
Louis.C

Reputation: 25

Bash - combine for loop variables and work to variables

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?

Upvotes: 1

Views: 121

Answers (1)

chepner
chepner

Reputation: 531235

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

Upvotes: 3

Related Questions