如何将地图数据结构作为参数传递给 Bash 脚本中的方法

Vam*_*lli 5 linux bash shell

我想创建一个像 Map 这样的数据结构 Person 并希望将其传递给 bash 脚本中的函数。在该方法中,我想检索 \xe2\x80\x9cPerson\xe2\x80\x9d ,例如 Person[Name] 、Person[Age] 、Person [Dept] 分别为 Mark 、 10 和 Finance 。等等,但我无法获取评论中提到的输出。这里需要一些指导如何做到这一点或我做错了什么。

\n\n

这是脚本

\n\n
#!/bin/bash -e\ngetValue(){\n    local Person=$1\n    echo Person[Name]\n}\n\nPerson[Name]=\xe2\x80\x9dMark\xe2\x80\x9d\nPerson [Age]=\xe2\x80\x9d10\xe2\x80\x9d\nPerson [Dept]=\xe2\x80\x9dFinance\xe2\x80\x9d\necho ${Person[Name]}   # why is  it printing Finance.I am expecting it to be printed as Mark   \n\ngetValue Person               # output is coming as Person\ngetValue ${Person}         # output is coming as  Finance\ngetValue  ${Person[@]} # output is coming as  Finance\n
Run Code Online (Sandbox Code Playgroud)\n

小智 5

您必须将 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"
Run Code Online (Sandbox Code Playgroud)

  • 是的,这就是为什么我说“如果你使用的是 `bash` 4.3 或更高版本”。 (2认同)