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?

3
  • 1
    You can use echo ${!a} This is introduces a level of variable indirection. Commented Dec 10, 2016 at 3: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. Commented Dec 10, 2016 at 3:54
  • Possible duplicate of Bash dynamic variable names Commented Dec 10, 2016 at 3:59

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.