bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: nounset option: Error message points to the wrong variable when acce


From: Emanuele Torre
Subject: Re: nounset option: Error message points to the wrong variable when accessing associative arrays
Date: Wed, 10 May 2023 20:21:56 +0200
User-agent: Mutt/2.2.10 (2023-03-25)

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



reply via email to

[Prev in Thread] Current Thread [Next in Thread]