Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

export

hash

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.

like image 697
Adam S Avatar asked Oct 17 '12 22:10

Adam S


People also ask

Does bash have associative arrays?

Bash, however, includes the ability to create associative arrays, and it treats these arrays the same as any other array. An associative array lets you create lists of key and value pairs, instead of just numbered values.

Is hash associative array?

The difference between an associative array and a hash table is that an associative array is a data type, while a hash table is a data implementation. Obviously the associative array type is very important in many current programming languages: Perl, Python, PHP, etc.

How do I export an environment variable in bash?

The easiest way to set environment variables in Bash is to use the “export” keyword followed by the variable name, an equal sign and the value to be assigned to the environment variable.

What is associative array in bash?

3 years ago. An array variable is used to store multiple data with index and the value of each array element is accessed by the corresponding index value of that element. The array that can store string value as an index or key is called associative array.


1 Answers

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)

like image 114
Gilles Quenot Avatar answered Oct 05 '22 21:10

Gilles Quenot