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

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[@]}" 

There isn't really a good way to encode an array variable into the environment. See http://www.mail-archive.com/[email protected]/msg01774.html (Chet Ramey is the maintainer of bash)

Tags:

Hash

Bash

Export