Bash array export workaround

末鹿安然 提交于 2020-05-31 02:14:38

问题


We know that exporting arrays in a canonical way is impossible, but I am interested in finding a workaround. I have a following scenario: a list of variables is loaded from a file to an array during startup, and I need to have that array visible to several bash scripts that may or may not be executed in the parent environment (. example.sh or just example.sh). I tried many things, but something like this seems as most promising:

export j=1
export array$j=something

And then I tried to access the value using:

echo ${array[$j]}      #doesn't work in child script
echo $(echo \$array$j) #displays the actual '$array1' instead of 'something'

Any suggestions?


回答1:


You can look up values through indirection using parameter expansion:

j=1
array1=something

name="array$j"
echo "The value of $name is ${!name}"


来源:https://stackoverflow.com/questions/24071377/bash-array-export-workaround

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!