Skip to content
koalaman edited this page May 13, 2015 · 6 revisions

To expand via indirection, use name="foo$n"; echo "${!name}".

Problematic code:

var_1="hello world"
n=1
echo "${var_$n}"

Correct code:

var_1="hello world"
n=1
name="var_$n"
echo "${!name}"

Rationale:

You can expand a variable var_1 with ${var_1}, but you can not generate the string var_1 with an embedded expansion, like var_$n. Instead, you have to use an indirect reference.

You can do this by creating a variable containing the variable name you want, e.g. myvar="var_$n" and then expanding it indirectly with ${!myvar}. This will give the contents of the variable var_1.

Exceptions:

None

ShellCheck

Each individual ShellCheck warning has its own wiki page like SC1000. Use GitHub Wiki's "Pages" feature above to find a specific one, or see Checks.

Clone this wiki locally