I set the a array as an environment variable in this manner
eg. script test.sh
in test.sh
#!/bin/bash
export STRING=( \"str1\" \"str2\"
The environment variables passed from processes to their children are unstructured strings; arrays cannot be supported. You can demonstrate this in Bash:
export x=foo
printenv x
That outputs foo
. If I now cause x
to become an array
x=(foo bar)
printenv x
We see no output (x
is not exported).
This says passing array as env variable is possible with bash script though. It works for defining and dereferencing the array in bash command, but it does not work when dereferencing from bash script (ubuntu 18.04).
The misunderstanding is in thinking that environment variables are only used by shells - they are not. No attributes, including readonly, integer, and arrays, can be exported into the environment block. Environment variables may be read by any language, C, C++, Perl, Java, Python, PHP, and so on. They also exist on Windows.
So, how could another language support Bash specific attributes? All environment variables are converted to strings, except in Bash where array values are not exported at all.
Korn shell will export just the first element. ksh93 also does some exec
exploitation to preserve variable attributes exported to Korn shell children.
By the way, it is considered bad practice to use UPPERCASE for variable names, since they could collide with those used by the shell. Also, on Bash 3, the name STRING has issues when exported (fixed in Bash 4).
You're trying to put an array into an environment variable, and environment variables can only be strings. bash doesn't have a method for properly serializing/deserializing arrays; do so manually.
Read the fine manual, "bugs" section.
Array variables may not (yet) be exported.
Though, I don't know that many consider this an actual bug. Other shells that support ksh-style arrays don't allow exporting them either.
You may pass around array definitions rather easily, through parameters or variables or the environment. It isn't usually very useful though.
function f {
unset -v "$2"
typeset "$2"
eval "${!1}"
typeset -p "$2"
}
typeset -a a=(a b c)
myArr=$(typeset -p a) f myArr a