mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Created SC2149 (markdown)
41
SC2149.md
Normal file
41
SC2149.md
Normal file
@@ -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.
|
Reference in New Issue
Block a user