如何在bash中导出关联数组(哈希)?

Ada*_*m S 9 bash hash export

相关但不重复:如何在Bash中定义哈希表?

我可以定义和使用bash哈希,但我无法导出它,即使使用-x标志.例如,以下工作用于导出(并测试输出)正常的字符串变量:

aschirma@graphics9-lnx:/$ export animal_cow="moo"
aschirma@graphics9-lnx:/$ bash -c "echo \$animal_cow"
moo
aschirma@graphics9-lnx:/$ 
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试导出哈希:

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:/$ 
Run Code Online (Sandbox Code Playgroud)

似乎嵌套的bash shell在其范围内没有哈希.我也通过手动输入嵌套的bash shell并尝试以交互方式使用哈希来验证这一点.

Gil*_*not 6

将数组变量编码到环境中并不是一种好方法.请参阅 http://www.mail-archive.com/bug-bash@gnu.org/msg01774.html(Chet Ramey是bash的维护者)

  • 再深入一点,环境是由操作系统定义的;shell 只是提供一种填充环境的方法。POSIX(作为示例)不为其环境变量提供结构化数据的定义;每个值只是一个字符串。“bash”将数组(常规或关联)转换为单个字符串的任何尝试都将特定于“bash”。这造成了可移植性的噩梦,因为环境不再简单地由操作系统定义,而是由任何用户可能决定用来启动程序的任何方法定义。 (4认同)

Loo*_*pes 5

作为这种严酷的 Bash 限制的解决方法,我使用“序列化到临时文件”方法。您可以导出普通变量,因此您可以通过文件路径传递数组(关联)。当然,这有局限性,但有时有效并且足够好。

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[@]}" 
Run Code Online (Sandbox Code Playgroud)