Remove all elements from associative array Bash

Viewed 1969

I need to remove all of the keys and values from an associative array in Bash. GNU bash, version 4.4.20(1)-release (x86_64-pc-linux-gnu). I cannot just unset it, because I need to do this inside a function. If I unset it, and then declare it again, it will only be local to the function.

arrayFunction()
{
    # Start the array Clearer
    unset workingArray
    declare -A workingArray
    # End the array Clearer

    workingArray[test]="bar"
    echo "Inside the function: ${workingArray[test]}"
}

declare -A workingArray

workingArray[test]="foo"

echo "Before the function: ${workingArray[test]}"

arrayFunction

echo "After the function: ${workingArray[test]}"

Output:

Before the function: foo
Inside the function: bar
After the function:

That last line of the output should be bar.

What I am looking for is some code to put inside the function that will empty the array ENTIRELY, while keeping the array global.

2 Answers

Well it's not really complex, just use -g.

Inside your function:

declare -gA workingArray

and this will happen gloabally.

The question ask to "remove all of the keys and values". However, from the sample code, it looks as if the request is to REPLACE all existing keys and values with new set of keys/values. This can be achieved with assignment to the associative array.

arrayFunction()
{
    workingArray=( [test]="bar" )
    echo "Inside the function: ${workingArray[test]}"
}

If the new key/values set is dynamic, it can be build incrementally

arrayFunction()
{
    # Start with empty set
    workingArray=()
    workingArray[test]=bar
    workingArray[lazy]=dog
    # Additional assignments
    echo "Inside the function: ${workingArray[test]}"
}

In both cases, there is no need to re-declare the array.

Related