bash - 从关联数组 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
.
我正在寻找的是一些放入函数中的代码,这些代码将完全清空数组,同时保持数组全局。
解决方案
好吧,它并不是很复杂,只需使用-g
.
在你的函数里面:
declare -gA workingArray
这将在全球范围内发生。
推荐阅读
- javascript - 为什么我尝试向用户显示警报会引发错误?
- python - 如何在pygame中使用操纵杆使精灵向上和向下移动
- java - 如何同步线程的结果 - Java 11
- python - 如何检查列表中的任何单词是否在列中的每一行中
- python - 如何修改此代码以打印等效项?
- backbone.js - 升级到主干 1.3.3 后主干模型属性嵌套两次
- python - 如何用字典保存类的对象以进行设置
- javascript - 我从一个扩展脚本收到一条消息到另一个,我可以 alert() 消息,但我不能将它分配给任何变量
- angularjs - $routeChangeSuccess 内部指令不会触发
- swift - 我如何将数据注入或添加到我的表中,因为它不起作用?