On Wed, May 10, 2023 at 05:44:54PM +0000, Baumann, Moritz wrote:
> In the case that lead me to submit this report, the error even occurred
> inside a check for the existence of an array key, which made the resulting
> message even weirder:
>
> if [[ -v "mistyped_array[$1]" ]]; then
> ...
> fi
⚠️ STOP USING [[ -v "assoc[$key]" ]]! DO NOT USE IT! ⚠️
[[ -v "assoc[$key]" ]], just like [[ -v assoc[$key] ]] makes no sense
and is just wrong:
$ key='$(echo hello >&2; echo hi)'
$ declare -A assoc=( [$key]=bar boo=ba )
$ declare -p assoc
declare -A assoc=([boo]="ba" ["\$(echo hello >&2; echo hi)"]="bar" )
$ [[ -v "assoc[$key]" ]]; echo "$?"
hello
1
$ assoc[foo]=123
$ [[ -v "assoc[$key]" ]]; echo "$?"
hello
0
$ key='${'
$ assoc[$key]=456
$ [[ -v "assoc[$key]" ]]; echo "$?"
1
Use [[ -v 'assoc[$key]' ]] instead, so that -v can expand the variable
correctly by itself:
$ key='$(echo hello >&2; echo hi)'
$ declare -A assoc=( [$key]=bar boo=ba )
$ declare -p assoc
declare -A assoc=([boo]="ba" ["\$(echo hello >&2; echo hi)"]="bar" )
$ [[ -v 'assoc[$key]' ]]; echo "$?"
0
$ assoc[foo]=123
$ [[ -v 'assoc[$key]' ]]; echo "$?"
0
$ key='${'
$ assoc[$key]=456
$ [[ -v "assoc[$key]" ]]; echo "$?"
0
Also, especially since you are using $1 in this case, you probably want
to make sure that $1 is not empty, because oterwise assoc[$key] is an
error. You cannot have empty associative array keys in bash:
$ key=
$ [[ -v 'assoc[$key]' ]]; echo "$?"
bash: assoc: bad array subscript
1
$ [[ $key && -v 'assoc[$key]' ]]
if [[ $1 && -v 'assoc[$1]' ]]; then
...
fi
emanuele6