简体   繁体   English

Bash:关联数组的值可以是数组吗? 它的语法是什么?

[英]Bash: Can the values of an associative array be arrays? What's its syntax?

I have an associative array stored in a bash file, and I'd like the values of said associative array to be arrays, but I don't even know if that's possible: 我在bash文件中存储了一个关联数组,并且我希望所述关联数组的值是数组,但是我什至不知道这是否可行:

Let's say I have the file /tmp/conf.bash containing: 假设我有/tmp/conf.bash文件, /tmp/conf.bash包含:

declare -A ASSOCIATIVE=( ["foo"]=( "bar" "baz" ) ) When I tried to load it (using source /tmp/conf.bash ) I get: declare -A ASSOCIATIVE=( ["foo"]=( "bar" "baz" ) )尝试加载它(使用source /tmp/conf.bash )时,我得到:

borrajax@wharrgarbl:~# source /tmp/conf.bash bash: /tmp/conf.bash: line 2: syntax error near unexpected token `(' bash: /tmp/conf.bash: line 2: ` ["foo"]=( "bar" "baz" )' bash: /tmp/conf.bash: line 3: syntax error near unexpected token `)' bash: /tmp/conf.bash: line 3: ` )'

But, if I make the file: 但是,如果我制作文件:

declare -A ASSOCIATIVE=(
    ["foo"]="bar baz"
 )

It works correctly: 它可以正常工作:

borrajax@wharrgarbl:~# source /tmp/conf.bash
borrajax@hwharrgarbl:~# for key in "${!ASSOCIATIVE[@]}"; do \
                        echo "key: $key; values: ${ASSOCIATIVE[$key]}"; \
                        done
key: foo; values: bar baz

Is there a way of specifying that the values are arrays in a Bash script? 有没有一种方法可以指定值是Bash脚本中的数组?

One possibility is set the values of the associative array as comma-separated strings and then split them into an array, but I thought maybe there's a way of formatting the bash file so that step is unnecessary. 一种可能是将关联数组的值设置为逗号分隔的字符串,然后将其拆分为一个数组,但是我认为也许有一种格式化bash文件的方法,因此无需执行此步骤。

I'm using Bash 4.2.28 我正在使用Bash 4.2.28

Thank you in advance. 先感谢您。

No. The values in an array (whether indexed or associative) can only be strings. 不能。数组中的值(无论是索引的还是关联的)只能是字符串。 It helps to think of bash arrays not as data structures, but a second level of quoting so that something like 它有助于将bash数组不视为数据结构,而是第二级引用,以便

args=("foo bar" "baz")
mycommand "${args[@]}"

passes two arguments, not three, to mycommand . 将两个参数而不是三个参数传递给mycommand In this scenario, nesting is not required, since a command can only take strings, not arrays, as arguments. 在这种情况下,不需要嵌套,因为命令只能将字符串而不是数组作为参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM