From d079d45e39d2698848bbf67899e45b4258bb6922 Mon Sep 17 00:00:00 2001 From: koalaman Date: Sat, 16 Aug 2014 17:07:28 -0700 Subject: [PATCH] Created SC2149 (markdown) --- SC2149.md | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 SC2149.md diff --git a/SC2149.md b/SC2149.md new file mode 100644 index 0000000..f21e70f --- /dev/null +++ b/SC2149.md @@ -0,0 +1,41 @@ +## Remove $/${} for numeric index, or escape it for string. + +### Problematic code: + + # Regular array + index=42 + echo $((array[$index])) + +or + + # Associative array + index=banana + echo $((array[$index])) + +### Correct code: + + # Regular array + index=42 + echo $((array[index])) + +or + + # Associative array + index=banana + echo $((array[\$index])) + +### Rationale: + +For a numerically indexed array, the `$` is mostly pointless and can be removed like in [[SC2004]]. + +For associative arrays, the `$` should be escaped to avoid accidental dereferencing: + + declare -A array + index='$1' + array[$index]=42 + echo "$(( array[$index] ))" # bash: array: bad array subscript + echo "$(( array[\$index] ))" # 42 + +### Contraindications + +None. \ No newline at end of file