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

标签 linux bash shell

我想创建一个类似 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/

相关文章:

linux - 如何将 sed 与需要转义的变量一起使用

linux - 在 Ubuntu-16.04 上从源代码安装 gcc-4.8.1

linux - 网络管理器 : where is the specification for its DBus interface?

linux - 在行的中间添加文本

linux - 如何在bash中将一个txt文件中的文件名重命名为另一个txt文件中的文件名?

java - 无法从 Java 程序执行 shell 脚本

linux - 如何在 linux 服务器上安排 .sh 脚本?

bash - 如何遍历目录中的文件并更改路径并为文件名添加后缀

perl - 如何检查 unix 时间早了 1 天

shell - Npm run 在 crontab (cronjob) 中不起作用