[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] Unsetting members of associative arrays
From: |
Douglas Lewan |
Subject: |
Re: [Help-bash] Unsetting members of associative arrays |
Date: |
Thu, 11 Apr 2019 19:16:59 -0400 |
User-agent: |
Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Icedove/52.9.1 |
On 04/11/2019 01:41 PM, Greg Wooledge wrote:
> 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
I agree quoting could be an issue and is certainly a matter of good
style. (My impatience to ask the question led to an incomplete example
and bad style, please forgive me.)
Here's a more complete example.
unset array
declare -A array
array[bob]=carol
array[ted]=alice
for v in 1 2 ; do
for i in "address@hidden" ; do
if [[ ${array["${i}"]} = alice ]] ; then
echo "It's alice."
if unset array["${i}"] ; then
echo "success"
else
echo "failure"
fi
else
echo "It's not alice."
fi
echo "After ${v},${i}: address@hidden"
done
echo "After ${v}: address@hidden"
done
echo "At end: address@hidden"
On 04/11/2019 01:42 PM, Jesse Hathaway wrote:
> That code works for me on Bash 5.0.3, or am I misunderstanding
> your question?
I'm using bash, version 4.3.48; I should have mentioned that.
Well, as with so many things Linux, once something has been threatened,
it becomes irreproducible. Now every variant I can think of on the above
code acts the way I want.
Thanks for the help.
--
,Doug
Douglas Lewan
+1 (908) 720-7908
The trouble with the world is that the stupid are cocksure and the intelligent
full of doubt. - Bertrand Russell