我想创建一个类似 Map 的数据结构 Person,并想将其传递给 bash 脚本中的函数。在方法中,我想检索“Person”,如 Person[Name] 、Person[Age] 、Person [Dept] as 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
最佳答案
您必须将 Person 定义为关联数组。 如果您使用的是 bash 版本 4 或更高版本,这里是运行代码。
#!/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"
关于linux - 如何将 map 数据结构作为参数传递给 Bash 脚本中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49901305/