如何在Bash脚本中将Map数据结构作为参数传递给方法

5
我希望创建一个类似于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

1
除非您使用declare -A,否则Person是一个索引数组。在每个赋值中,您的键都在算术上下文中进行评估,每个未定义的名称默认为0。因此,您有Person[0]=MarkPerson[0]=10Person[0]=Finance。同样,${Person[Name]}${Person[0]}相同,最后一次分配给索引0的是Finance - chepner
1个回答

5

你需要将Person定义为一个关联数组。 如果你正在使用4或以上版本的bash,这里是运行代码。

#!/bin/bash -e
function getValue(){
        person=$(declare -p "$1")
        declare -A person_arr=${person#*=}
        echo ${person_arr[Name]} 
        echo ${person_arr[Age]} 
        echo ${person_arr[Dept]} 
}

declare -A Person
Person[Name]="X"
Person[Age]=10
Person[Dept]="Finance"
echo ${Person[Name]}  
echo ${Person[Age]}  
echo ${Person[Dept]} 
getValue "Person"

1
如果您使用的是 bash 4.3 或更高版本,则可以使用命名引用来简化此过程。declare -n person=$1; echo ${person[Name]};. - chepner
1
在4.3版本之前,我会使用间接扩展,因为它可能比使用declare -p的输出更健壮。 name ="$ 1 [Name]"; echo "$ {!name} - chepner
谢谢。已经注意到了。在我的版本4.2.46中,“declare -n”选项无法工作,会出现“-n:无效选项”的错误。 - utpal416
2
是的,这就是为什么我说“如果您使用的是bash 4.3或更高版本”。 - chepner
我在这行代码 person=$(declare -p "$1") 中收到了 declare: :未找到 的错误,使用的是 bash 4.2.46 - papanito

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接