How to export an associative array (hash) in bash?

后端 未结 3 1726
梦毁少年i
梦毁少年i 2020-12-16 16:27

Related, but not a duplicate of: How to define hash tables in Bash?

I can define and use a bash hash, but I am unable to export it, even with the -x flag. For examp

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-16 17:02

    As a workaround for this harsh Bash limitation I'm using "serialize to temporary file" method. You can export plain variables, so you can pass an array (associative) through filepath. Of course, this has limitations, but sometimes works and is good enough.

    declare -A MAP # export associative array                                                                           
    MAP[bar]="baz"                                                                        
    declare -x serialized_array=$(mktemp) # create temporary variable 
    # declare -p can be used to dump the definition 
    # of a variable as shell code ready to be interpreted                                       
    declare -p MAP > "${serialized_array}" # serialize an array in temporary file 
    
    # perform cleanup after finishing script                                      
    cleanup() {                                                                   
      rm "${serialized_array}"                                                    
    }                                                                             
    trap cleanup EXIT   
    
    # ... in place where you need this variable ...
    source "${serialized_array}" # deserialize an array                         
    echo "map: ${MAP[@]}" 
    

提交回复
热议问题