"${array[$key]}"
vs "${array["$key"]}"
?
Typically I quote all bash variables as a default, with purposed exceptions. What about when specifying a key for an associative array? I see that in simple cases, keys can have spaces and there doesn't seem to be any word splitting issues without quotes, but shell frequently has obscure situations where constructs have caveats.
There are lot of extra characters in "${array[$key]}"
and moreso "${array["$key"]}"
. Is there any reason it would be a bad habit to leave variables unquoted in the index field of an associative array reference?
CodePudding user response:
Variables in a subscript of an associative array need not be quoted.
If double quotes are used, they will be removed (whether the entire array variable is also quoted, or not). So you can double quote if you want, but it doesn't do anything.
Single quotes will stop expansion of the variable (containing the array subscript), as normal.
man bash
> Arrays
associative arrays are referenced using arbitrary strings
Also note, indexed arrays subscripts are evaluated as arithmetic, meaning $
is not necessary for variables used in the subscript.