Bash: set env variable of array and remove link from any shell script fails

I set the array as an environment variable this way for example. script test.sh

in test.sh

 #!/bin/bash export STRING=( "str1" "str2" ) 

source test.sh

now in script test-1.sh

 #!/bin/bash echo ${STRING[0]} 

the answer is nothing, just an empty string, whereas if I try to set STRING="str1" in test.sh and echo $STRING in test-1.sh , this works.

tests are performed only by the root user. Now, how to set the array as an env variable so that I can call the elements of the array as required? Before, I even tried to modify /etc/bashrc , which also did not lead to anything positive.

I need to set the array as an env variable, since there can be many scripts that I need to write that these variable parameters should use.

Can someone give me suggestions for correcting me, where am I doing wrong?

+7
source share
4 answers

Read the detailed manual, the error section.

Array variables cannot (yet) be exported.

Although, I do not know that many consider this a real mistake. Other shells that support arrays of the ksh type also do not allow exporting them.

You can pretty easily pass array definitions through parameters or variables or the environment. This is usually not very useful.

 function f { unset -v "$2" typeset "$2" eval "${!1}" typeset -p "$2" } typeset -aa=(abc) myArr=$(typeset -pa) f myArr a 
+10
source

The misunderstanding is that environment variables are used only by shells - they are not. No attributes, including readonly, integer, and arrays, can be exported to the environment block. Environment variables can be read in any language, C, C ++, Perl, Java, Python, PHP, etc. They also exist on Windows.

So, how can another language support Bash specific attributes? All environment variables are converted to strings, with the exception of Bash, where array values ​​are not exported at all.

The Korn shell exports only the first item. ksh93 also performs some exec operation to save the variable attributes exported to children of the Korn shell.

By the way, it is considered bad practice to use UPPERCASE for variable names, as they may interfere with those used by the shell. In addition, in Bash 3, the name STRING has problems exporting (fixed in Bash 4).

+2
source

You are trying to put an array in an environment variable, and environment variables can only be strings. bash does not have a method to properly serialize / deserialize arrays; do it manually.

0
source

Environment variables passed from processes to their children are unstructured lines; arrays are not supported. You can demonstrate this in Bash:

 export x=foo printenv x 

This displays foo . If I now call x to become an array

 x=(foo bar) printenv x 

We do not see output ( x not exported).

0
source

All Articles