简体   繁体   English

BASH:如何在调用bash脚本之前将数组定义为环境变量

[英]BASH: how to define an array as environment variable before calling a bash script

In bash, you can do 在bash中,你可以做到

MYVAR="somevalue" ./myscript.sh

and the variable MYVAR will be defined when running myscript.sh. 并且在运行myscript.sh时将定义变量MYVAR。

My questions is: can I do the same for arrays? 我的问题是:我可以为数组做同样的事情吗? Unfortunately, neither of the following works. 不幸的是,以下都不起作用。

MYARR=( 1 2 ) ./myscript.sh
MYARR[0]=1 MYARR[1]=2 ./myscript.sh
declare -a MYARR=( 1 2 ) ./myscript.sh

Incredibility weird.... I have never seen that before. 令人难以置信的奇怪......我以前从未见过。

It looks like the array is not passed to the subshell. 看起来数组没有传递给子shell。 One way around this is to source the script instead of executing it: 解决此问题的一种方法是获取脚本而不是执行它:

declare -a MYARR=( 1 2 ); . ./myscript.sh

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM