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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14370133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:13:35  来源:igfitidea点击:

Is there a way to create key-value pairs in Bash script?

bashshellassociative-array

提问by RKS

I am trying to create a dictionary of key value pair using Bash script. I am trying using this logic:

我正在尝试使用 Bash 脚本创建一个键值对字典。我正在尝试使用这种逻辑:

declare -d dictionary
defaults write "$dictionary" key -string "$value"

...where $dictionaryis a variable, but this is not working.

... where$dictionary是一个变量,但这不起作用。

Is there a way to create key-value pairs in Bash script?

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

回答by peteches

In bash version 4 associative arrays were introduced.

在 bash 版本 4 中引入了关联数组。

declare -A arr

arr["key1"]=val1

arr+=( ["key2"]=val2 ["key3"]=val3 )

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.

arr 数组现在包含三个键值对。但是,Bash 可以用它们做的事情相当有限,没有排序或弹出等。

for key in ${!arr[@]}; do
    echo ${key} ${arr[${key}]}
done

Will loop over all key values and echo them out.

将遍历所有键值并将它们回显出来。

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

注意:由于 Mac OS X 的 GPLv3 许可,Bash 4 不附带;你必须下载并安装它。有关更多信息,请参见此处

回答by math

If you can use a simple delimiter, a very simple oneliner is this:

如果你可以使用一个简单的分隔符,一个非常简单的单行是这样的:

for i in a,b c_s,d ; do 
  KEY=${i%,*};
  VAL=${i#*,};
  echo $KEY" XX "$VAL;
done

Hereby iis filled with character sequences like "a,b"and "c_s,d". each separated by spaces. After the dowe use parameter substitutionto extract the part before the comma ,and the part after it.

这里i充满了像"a,b"和这样的字符序列"c_s,d"。每个都用空格隔开。在之后do我们使用参数替换来提取逗号之前,的部分和它之后的部分。

回答by andrej

For persistent key/value storage, you can use kv-bash, a pure bash implementation of key/value database available at https://github.com/damphat/kv-bash

对于持久键/值存储,您可以使用kv-bash,这是一个纯 bash 实现的键/值数据库,可在https://github.com/damphat/kv-bash

Usage

用法

git clone https://github.com/damphat/kv-bash
source kv-bash/kv-bash

Try create some permanent variables

尝试创建一些永久变量

kvset myName  xyz
kvset myEmail [email protected]

#read the varible
kvget myEmail

#you can also use in another script with $(kvget keyname)
echo $(kvget myEmail)