arrays - Bash 数组键与现有变量冲突

标签 arrays bash

我的期望是 bash 数组中的键被解释为文字,但似乎并非如此。例如,以下按预期工作:

$ declare -a mymap
$ mymap[foo]="bar"

没问题,我们现在有一个带有键的数组,字面意思是 “foo”。但是当我设置一个与键同名的环境变量,并在其中放入特殊字符时,它会产生解析错误:

$ declare -a mymap
$ export foo=" > "
$ mymap[foo]="bar"
-bash: >: syntax error: operand expected (error token is ">")
$ mymap["foo"]="bar"
-bash: >: syntax error: operand expected (error token is ">")
$ mymap['foo']="bar"
-bash: >: syntax error: operand expected (error token is ">")

谁能解释一下我在这里缺少什么?我使用的是 bash 版本 4.3.33。

最佳答案

使用-A 声明一个带有字符串键的关联数组。 -a 创建一个索引数组,其键在算术上下文中计算。

$ declare -A mymap
$ export foo=' > '
$ mymap[foo]="bar"
$ echo "${mymap[foo]}"
bar
$ declare -p mymap
declare -A mymap='([foo]="bar" )'

关于arrays - Bash 数组键与现有变量冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29906615/

相关文章:

java - 无法正确将 Base64 MIME 图像解码为字节数组 (Java)

bash - 使用外部项目文件夹中的 Composer

bash - Shell 脚本 zenity - 检查是否取消

linux - 在 Bash 中捕获逻辑的返回输出

PHP选择多个数组表

java - 插入时排序 vs 稍后对整个数组进行排序

php - Cakephp如何删除链接上的下划线

c++ - Valgrind 在定义 char* 数组时报告内存泄漏

bash - Kubernetes cloudsql 中使用特殊字符转义密码的问题

bash - 服务器错误 (NotFound) : pods "\nmongo-client-79667cc85d-tsg72" not found