相关但不重复:如何在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并尝试以交互方式使用哈希来验证这一点.
将数组变量编码到环境中并不是一种好方法.请参阅 http://www.mail-archive.com/bug-bash@gnu.org/msg01774.html(Chet Ramey是bash的维护者)
作为这种严酷的 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)