有没有办法在 Bash 脚本中创建键值对? [英] Is there a way to create key-value pairs in Bash script?

查看:47
本文介绍了有没有办法在 Bash 脚本中创建键值对?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 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 脚本中创建键值对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆