You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Vidar Holen edited this page Dec 31, 2020
·
1 revision
For indirection, use arrays, declare "var$n=value", or (for sh) read/eval
Problematic code:
n=1
var$n="hello"
Correct code:
For integer indexing in ksh/bash, consider using an indexed array:
n=1
var[n]="hello"echo"${var[n]}"
For string indexing in ksh/bash, use an associative array:
typeset -A var
n="greeting"
var[$n]="hello"echo"${var[$n]}"
If you actually need a variable with the constructed name in bash, use declare:
n="Foo"declare"var$n=42"echo"$varFoo"
For sh, with single line contents, consider read:
n="Foo"read -r "var$n"<<EOFhelloEOFecho"$varFoo"
or with careful escaping, eval:
n=Foo
eval"var$n='hello'"echo"$varFoo"
Rationale:
var$n=value is not a valid way of assigning to a dynamically created variable name in any shell. Please use one of the other methods to assign to names via expanded strings. Wooledge BashFaq #6 has significantly more information on the subject.
Exceptions:
None
Related resources:
Wooledge BashFaq #6: How can I use variable variables (indirect variables, pointers, references) or associative arrays?