7

In bash, you can do

MYVAR="somevalue" ./myscript.sh

and the variable MYVAR will be defined when running myscript.sh.

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
1
  • Just note that passing arrays through environment variables won't work because environment variables are always strings. Arrays don't fit there. Commented Aug 8, 2013 at 20:34

1 Answer 1

7

Incredibility weird.... I have never seen that before.

It looks like the array is not passed to the subshell. One way around this is to source the script instead of executing it:

declare -a MYARR=( 1 2 ); . ./myscript.sh
Sign up to request clarification or add additional context in comments.

3 Comments

Nice, this works! Does sourcing have any drawbacks except for the fact that the shell is closed when myscript.sh calls exit?
Your shell will also retain any variables, functions, and mode settings etc left from the script. For example, if it does a set -f, filename wildcards won't work for you until you turn that option back off. You can avoid this (and the exit problem) by running it in a subshell by putting ( ... ) around the relevant section.
Yes, I am aware of that, thanks. I was using xterm -e "..." so this is not an issue. Unfortunately, however, I cannot do xterm -e "MYARR=( 1 2 ); . ./myscript.sh || read -p \"Error: print [Enter] to continue.\"" anymore. And xterm does not return the exit value of the executed command.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.