From b17abf441529674142322650800d3769298adb31 Mon Sep 17 00:00:00 2001 From: koalaman Date: Wed, 13 May 2015 11:50:47 -0700 Subject: [PATCH] Created SC2082 (markdown) --- SC2082.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 SC2082.md diff --git a/SC2082.md b/SC2082.md new file mode 100644 index 0000000..f955ad8 --- /dev/null +++ b/SC2082.md @@ -0,0 +1,24 @@ +## 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 \ No newline at end of file