help-bash
[Top][All Lists]
Advanced

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

Re: [Help-bash] Unsetting members of associative arrays


From: Greg Wooledge
Subject: Re: [Help-bash] Unsetting members of associative arrays
Date: Thu, 11 Apr 2019 13:41:30 -0400
User-agent: Mutt/1.10.1 (2018-07-13)

On Thu, Apr 11, 2019 at 12:32:04PM -0400, Douglas Lewan wrote:
> The following code doesn't do what I expect. The ostensibly unset array
> element is still there. There's a work-around: Keep track of the indexes
> to unset and do that outside the loop.
> 
> declare -A array
> 
> for i in address@hidden ; do
> do
>       if [[ ${array[${i}]} = bob ]]
>       then
>               unset array[${i}]
>       fi
> done

Your quoting is incorrect in two places.

for i in "address@hidden"; do
  if [[ ${array[$i]} = bob ]]; then
    unset 'array[$i]'
  fi
done

> Is there a real reason for that or is it a bug?

If the properly quoted version doesn't fix your issues, then you'll
need to show us an example of the failure.  Including the contents of
the array before and after the loop.

Explanation of the quoting issues in detail:

The "address@hidden" must be quoted because the keys of an associative
array may contain spaces, glob characters, etc.  The unquoted expansion
would undergo word splitting and filename expansion which you do not
want.

The 'array[$i]' must be quoted because in the absence of quotes, the
index variable will be expanded, resulting in a word or series of
words.  If there's a space, you get a series of words, and that's clearly
broken.  If there's no space, you get a single word that has square brackets
in it.  This is a valid glob, so the shell will perform filename expansion,
matching against the files in the current working directory.  If any
files match, then you get a transformed argument and you may possibly
attempt to unset arraywilma or similar.  Only if NO files match (and
nullglob is not in effect) will the glob be untouched.

http://mywiki.wooledge.org/BashPitfalls#pf57



reply via email to

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