我正在尝试使用 Bash 脚本创建一个键值对字典.我正在尝试使用这种逻辑:
I am trying to create a dictionary of key value pair using Bash script. I am trying using this logic:
declare -d dictionary defaults write "$dictionary" key -string "$value"...其中 $dictionary 是一个变量,但这不起作用.
...where $dictionary is a variable, but this is not working.
有没有办法在 Bash 脚本中创建键值对?
Is there a way to create key-value pairs in Bash script?
推荐答案在 bash 版本 4 中引入了关联数组.
In bash version 4 associative arrays were introduced.
declare -A arr arr["key1"]=val1 arr+=( ["key2"]=val2 ["key3"]=val3 )arr 数组现在包含三个键值对.但是,Bash 可以用它们做的事情相当有限,没有排序或弹出等.
The arr array now contains the three key value pairs. Bash is fairly limited what you can do with them though, no sorting or popping etc.
for key in ${!arr[@]}; do echo ${key} ${arr[${key}]} done将遍历所有键值并将它们回显出来.
Will loop over all key values and echo them out.
注意: Bash 4 没有随 Mac OS X 一起提供,因为它的 GPLv3 许可证;你必须下载并安装它.有关更多信息,请参阅此处
Note: Bash 4 does not come with Mac OS X because of its GPLv3 license; you have to download and install it. For more on that see here
更多推荐
有没有办法在 Bash 脚本中创建键值对?
发布评论