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

bash, export, hash

Solution

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

Problem

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 example, the following works to export (and test exportation of) a normal string variable: ``` aschirma@graphics9-lnx:/$ export animal_cow="moo" aschirma@graphics9-lnx:/$ bash -c "echo \$animal_cow" moo aschirma@graphics9-lnx:/$ ``` However, if I try to export a hash: ``` aschirma@graphics9-lnx:/$ declare -A -x animals aschirma@graphics9-lnx:/$ animals[duck]="quack" aschirma@graphics9-lnx:/$ echo ${animals[duck]} quack aschirma@graphics9-lnx:/$ bash -c "echo \${animals[duck]}" aschirma@graphics9-lnx:/$ ``` It seems the nested bash shell does not have the hash in its scope. I did verify this also by manually entering the nested bash shell and attempting to use the hash interactively.

Original source

Related problems