有没有办法在 Bash 脚本中创建键值对?

编程入门 行业动态 更新时间:2024-10-28 03:31:26
本文介绍了有没有办法在 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 脚本中创建键值对?

本文发布于:2023-10-31 01:26:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1544584.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:没有办法   键值   脚本   Bash

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!