簡體   English   中英

如何將地圖數據結構作為參數傳遞給Bash腳本中的方法

[英]How to pass a Map Data Structure as an argument to a method in a Bash Script

我想創建一個像Map一樣的數據結構,並希望將它傳遞給bash腳本中的函數。 在方法中,我想分別檢索“人”,如人[姓名],人[年齡],人[部門]作為馬克,10和財務。 但是我無法獲得評論中提到的輸出。 在這里需要一些指導如何或我做錯了什么。

這是腳本

#!/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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM