首页 > 解决方案 > 从关联数组 Bash 中删除所有元素

问题描述

我需要从 Bash 的关联数组中删除所有键和值。GNU bash, version 4.4.20(1)-release (x86_64-pc-linux-gnu). 我不能只是unset它,因为我需要在函数内部执行此操作。如果我取消设置它,然后declare再次设置,它只会是函数的本地。

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]}"

输出:

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

输出的最后一行应该是bar.

我正在寻找的是一些放入函数中的代码,这些代码将完全清空数组,同时保持数组全局。

标签: bash

解决方案


好吧,它并不是很复杂,只需使用-g.

在你的函数里面:

declare -gA workingArray

这将在全球范围内发生。


推荐阅读