Bash. Initialize dynamic associative array

I have a bash code declaring an associative array. After the initialization, some vars are added to the array. Until here everything is working fine. The problem arises if the program reachs again the same function. The declare for the array is done again and what I want is that the data of the array is destroyed but it seems the declare statement is not destroying the data.

This PoC code shows what I mean.

#!/bin/bash

declare -gA myarray

myarray["testing"]="anyvalue"

for i in "${myarray[@]}"; do
    echo "${i}" # It prints "anyvalue", until here is ok
done

declare -gA myarray # At this point I want the array empty again!

for i in "${myarray [@]}"; do
    echo "${i}" # This is printing "anyvalue"!! and It should print nothing
done

echo "finished"

The output of this script is:

anyvalue
anyvalue
finished

The desired output is:

anyvalue
finished

I found this similar post. The problem of this post is that it seems it's needed to know the fixed length of the array. In my case (the real case, not the PoC code) the array can get dynamic values and elements and I don't know if it is going to have one value, or three, or twenty.

How can I initialize the array destroying its data without knowing how many data are inside? Thanks.

1 answer

  • answered 2018-11-07 23:09 oguzismail

    Use unset builtin of bash

    $ declare -gA myarray
    $ myarray["foo"]=bar
    $ echo ${myarray[@]}
    bar
    $ unset myarray
    $ echo ${myarray[@]}
    
    $ myarray["bar"]=foo
    $ echo ${myarray[@]}
    foo