首页 > 解决方案 > bash - 关联数组下标 - “不是有效的标识符”

问题描述

bash 是否对关联数组下标中使用的字符施加限制?我已经成功使用了包含空格的字符串下标,但是当下标包含引号时,我遇到了(错误?)。

bash-5.0$ declare -A x
bash-5.0$ x["bugs"]=yes
bash-5.0$ x["bug's"]=yes
bash-5.0$ for sub in "${!x[@]}"; do echo "$sub:" ${x["$sub"]}; done
bug's: yes
bugs: yes
bash-5.0$ if [[ -v x["bugs"] ]]; then echo exists; else echo does NOT exist; fi
exists
bash-5.0$ if [[ -v x["bug's"] ]]; then echo exists; else echo does NOT exist; fi
does NOT exist
bash-5.0$ unset x[bugs]
bash-5.0$ unset x["bug's"]
bash: unset: `x[bug's]': not a valid identifier
bash-5.0$ bash --version
bash --version
GNU bash, version 5.0.17(1)-release (x86_64-apple-darwin18.7.0)
Copyright (C) 2019 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
bash-5.0$ 

[忽略语法着色 - 这会误解输出。] 请注意分配成功进行,我可以遍历数组并打印其内容。但是第二个“if”语句工作不正确,最后一个“unset”命令失败并显示错误消息。

对我来说,这看起来像是 bash 中的一个错误。想法?

标签: arraysbashassociative

解决方案


推荐阅读