Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all elements from associative array Bash

Tags:

bash

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.

like image 706
Feldspar15523 Avatar asked Aug 31 '26 05:08

Feldspar15523


1 Answers

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

Inside your function:

declare -gA workingArray

and this will happen gloabally.

like image 54
Mihir Luthra Avatar answered Sep 05 '26 02:09

Mihir Luthra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!