Bash:从变量设置关联数组

问题描述 投票:0回答:3

我从命令行工具获取一些数据,并希望用数据填充关联数组。我可以改变返回的数据的格式,但是如何对关联数组?

content="[key1]=val1 [key2]=val2" # How should this be formatted?

declare -A hashTable
hashTable=($content) # How to set it?

declare -p hashTable
bash
3个回答
0
投票

如果你掌握qazxsw poi并理解bash解析,例如不是来自外部输入

content

否则你必须解析它以确保没有注入(因为eval重新解释数据作为代码,bash表达式),想象内容包含eval "hashTable=($content)" 作为示例给出

echo

也许更容易拆分content=');echo hey;x=('

content

0
投票

如果您接受格式化第一个命令的输出,就像这样

hashTable=()
tmp=$content
while [[ $tmp = *\[* ]] && tmp=${tmp#*\[} || tmp=; [[ $tmp ]]; do
    cur=${tmp%%\[*};
    val=${cur#*\]=};
    hashTable[${cur%%\]=*}]=${val%${val##*[![:space:]]}}
done

如果没有value2中的空格而没有'=',那么您可以尝试以下代码:

key1=value1 key2=value2

0
投票

执行此操作的最佳方法(需要#!/bin/bash content="key1=val1 key2=val2" declare -A hashTable for pair in $content ; do key=${pair%=*} # take the part of the string $pair before '=' value=${pair/#*=/} # take the part of the string $pair after '=' hashTable[$key]=$value done for K in "${!hashTable[@]}"; do echo hashTable\[$K\]=${hashTable[$K]}; done 4.4或更高版本)是让命令返回一个字符串,交替键和值,每个字符都以空字符结尾。然后,您可以使用bash将其解析为索引数组,然后从中构建关联数组。

readArray

$ readArray -t -d '' foo < <(printf 'key1\0value1\0key2\0value2\0') $ declare -p foo declare -a foo=([0]="key1" [1]="value1" [2]="key2" [3]="value2") $ for ((i=0; i < ${#foo[@]}; i+=2)); do > hashTable[${foo[i]}]=${foo[i+1]} > done $ declare -p hashTable declare -A hashTable=([key2]="value2" [key1]="value1" ) 4.4是bash-d选项所必需的。在早期的4.x版本中,您可以使用带有嵌入换行符的字符串,但这会阻止您自己的键或值包含换行符。

(请注意,在readArray的赋值中,你可以安全地保留hashTable${foo[i]}不加引号,因为键和值都不会进行单词拆分或路径名扩展。但是,如果你愿意,引用它们并没有什么坏处。)

© www.soinside.com 2019 - 2024. All rights reserved.