我希望创建一个类似于Map的数据结构Person,并希望将其传递给bash脚本中的函数。在该方法中,我希望像Person [Name],Person [Age],Person [Dept]这样检索“Person”,分别作为Mark、10和Finance。但是我无法得到输出,如评论中所述。需要一些指导,告诉我如何做或我做错了什么。
以下是脚本:
以下是脚本:
#!/bin/bash -e
getValue(){
local Person=$1
echo Person[Name]
}
Person[Name]=”Mark”
Person [Age]=”10”
Person [Dept]=”Finance”
echo ${Person[Name]} # why is it printing Finance.I am expecting it to be printed as Mark
getValue Person # output is coming as Person
getValue ${Person} # output is coming as Finance
getValue ${Person[@]} # output is coming as Finance
declare -A
,否则Person
是一个索引数组。在每个赋值中,您的键都在算术上下文中进行评估,每个未定义的名称默认为0。因此,您有Person[0]=Mark
,Person[0]=10
和Person[0]=Finance
。同样,${Person[Name]}
与${Person[0]}
相同,最后一次分配给索引0的是Finance
。 - chepner