From bdaa27c9fdd293ca4e4997303e8410ee3d4cb977 Mon Sep 17 00:00:00 2001 From: koalaman Date: Sun, 14 Jun 2015 17:19:03 -0700 Subject: [PATCH] Updated SC2082 (markdown) --- SC2082.md | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/SC2082.md b/SC2082.md index 1a6fe03..ffb294b 100644 --- a/SC2082.md +++ b/SC2082.md @@ -8,16 +8,39 @@ ### Correct code: +Bash/ksh: + + # Use arrays instead of dynamic names + declare -a var + var[1]="hello world" + n=1 + echo "${var[n]}" + +or + + # Expand variable names dynamically var_1="hello world" n=1 name="var_$n" echo "${!name}" +POSIX sh: + + # Expand dynamically with eval + var_1="hello world" + n=1 + eval "tmp=\$var_$n" + echo "${tmp}" + ### 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 expand a variable `var_1` with `${var_1}`, but you can not generate the string `var_1` with an embedded expansion, like `${var_$n}`. -You 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`. +Instead, if at all possible, you should use an array. Bash and ksh support both numerical and associative arrays, and an example is shown above. + +If you can't use arrays, you can indirectly reference variables by creating a temporary variable with its name, e.g. `myvar="var_$n"` and then expanding it indirectly with `${!myvar}`. This will give the contents of the variable `var_1`. + +If using POSIX sh, where neither arrays nor `${!var}` is available, `eval` can be used. You must be careful in sanitizing the data used to construct the variable name to avoid arbitrary code execution. ### Exceptions: