Is there a way to create key-value pairs in Bash script?

后端 未结 5 2089
不思量自难忘°
不思量自难忘° 2020-12-22 19:05

I am trying to create a dictionary of key value pair using Bash script. I am trying using this logic:

declare -d dictionary
defaults write \"$dictionary\" ke         


        
5条回答
  •  温柔的废话
    2020-12-22 19:31

    In bash version 4 associative arrays were introduced.

    declare -A arr
    
    arr["key1"]=val1
    
    arr+=( ["key2"]=val2 ["key3"]=val3 )
    

    The arr array now contains the three key value pairs. Bash is fairly limited what you can do with them though, no sorting or popping etc.

    for key in ${!arr[@]}; do
        echo ${key} ${arr[${key}]}
    done
    

    Will loop over all key values and echo them out.

    Note: Bash 4 does not come with Mac OS X because of its GPLv3 license; you have to download and install it. For more on that see here

提交回复
热议问题