arrays - bash 数组给了我不需要的前缀

标签 arrays linux bash

declare -A script_input=([name]=input [input]=inputs [output]=inputs )
declare -A script_output=([name]=output [input]=outputs [output]=outputs )
declare -a scripts=(script_output script_input )
echo ${script_output[input]}

结果是:

outputs

我希望从其他代码中得到类似的结果,但我没有:

script=${scripts[0]}
echo ${script[input]}

现在我明白了

script_output

我不明白为什么!

最佳答案

您可以使用 bash 间接语法这样做:

script=${scripts[0]}[input]
echo ${!script}

请注意,script 的值是数组元素的完整“名称”:

$ echo "$script"
script_output[input]

使用 bash v4.3,您可以使用 nameref 来避免这种摆弄:

# Make script a nameref
declare -n script=${scripts[0]}
# Now you can use script as though it were the named array
echo "${script[input]}"

关于arrays - bash 数组给了我不需要的前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29402850/

相关文章:

javascript - 映射数组以设置空元素

arrays - UserDefaults 无法正确检索我的字符串数组

javascript - React 无法读取属性值

linux - 如何从内核模块写入 TTY?

c - 为什么在 UNIX 中只分配最低的可用文件描述符?

c++ - 在 C++ 中,可以将多少个值放入数组中?

linux - 如果一个文件在边沿触发调用epoll_ctl之前是可读的,那么后续的epoll_wait是否会立即返回?

bash - bash vi shell 模式下的 Tab 自动补全

linux - 取消引用该变量并将其附加到其他字符串

linux - tar/gzip 不包括某些文件