1

I'm currently fighting with this problem.

I've already read some older posts here on SE, and got the conclusion that the only sane way to put a variable (even an array) is ~/.profile.
So OK, array shows up, simple things like echo ${myarray[12]} work fine, however, only on the console. myarray is a large string array with several dozen constant values, which I'd like to build up once instead of creating from scratch every time I run the script.

However, a simple check like echo "elems = ${#myarray[@]}" will always return 0, i. e. the array isn't known and empty.

But why is that so? I actually expected that variables declared in ~/.profile will be available also from shell scripts that I start in this environment. (Even from the very same tty it won't show the values from inside my script.)

2

Arrays aren’t environment variables, and so are not (and cannot be) inherited by children processes (such as scripts) from their parents.  You must “create [your array] from scratch every time you run your script.”  I don’t understand why you view this as a hardship.  If the values are constant, as you say, then all that needs to happen is for those values to get read into memory from the script.  If your concern is that the code to initialize the array clutters up your script, put it into a separate script file and call it with “.” or “source”.

I don’t know where you got the idea that “the only sane way to put [sic] a variable (even an array) is ~/.profile.”

  • I don’t understand why you view this as a hardship. Because the script might be called repeatedly in short intervals. And hence I thought it would be a nice idea to have an array pre-built which can then be used by all subsequent script calls. – syntaxerror Sep 15 '14 at 23:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.