简体   繁体   English

Bash数组和路径名扩展:奇怪的输出

[英]Bash arrays and pathname expansion: Weird output

I have two files in my home directory .phpsh and .php_history and using their names I wanted to test the expansion of pathnames and how it affects associative arrays in bash. 我的主目录.phpsh.php_history有两个文件,并使用它们的名称来测试路径名的扩展以及它如何影响bash中的关联数组。 The results I came across seemed weird and I couldn't quite explain them. 我遇到的结果看起来很奇怪,我无法完全解释。 I've tried a whole bunch of variations here. 我在这里尝试了很多变化。

 >my_array_filename_var=(".phpsh"=10 ".php_history" =20)
 >echo ${my_array_filename_var[.phpsh]}
 ERROR
 >echo "${my_array_filename_var[.phpsh]}"
 ERROR
 # This one below understandably doesn't work. But I was pulling my hair out.
 >echo "${my_array_filename_var[".phpsh"]}"
 ERROR
 echo "${my_array_filename_var[\".phpsh\"]}"
 ERROR
 >echo "${my_array_filename_var[.phpsh]}"
 ERROR
 >echo "${my_array_filename_var[phpsh]}"
 .phpsh=10
 >echo "${my_array_filename_var[php_history]}"
 .phpsh=10
 >echo "${my_array_filename_var[\.php_history]}"
 ERROR

where the ERROR token stands for ERROR令牌代表的位置

bash: .phpsh: syntax error: operand expected (error token is ".phpsh")

Is there some rule that says I can't have the dot character in my key for an associative array? 是否有一些规则说我不能在关联数组的键中包含点字符? How does pathname expansion in the bash play with this? bash中的路径名扩展如何与此一起玩?

You should declare -A (capital A) an associative array in bash. 您应该在bash中declare -A (大写A)一个关联数组。 This is the correct syntax: 这是正确的语法:

$ declare -A my_array_filename_var=([.phpsh]=10 [.php_history]=20)
$ echo "${my_array_filename_var[.phpsh]}"
10

Or 要么

$ declare -A my_array_filename_var
$ my_array_filename_var=([.phpsh]=10 [.php_history]=20)
$ echo "${my_array_filename_var[.phpsh]}"
10

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

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