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" )
source test.sh
now in script test-1.sh
#!/bin/bash
echo ${STRING[0]}
the response is nothing, just a blank line,
whereas, if I try to set STRING="str1"
in test.sh
and do echo $STRING
in test-1.sh
, this works.
tests are executed from root user only,
Now how to set array as env variable , so that I can call the elements of array as per requirement? Earlier, I have tried to even modify /etc/bashrc
and that also didn't result in anything positive.
I need to set the array as env variable as there may be many scripts that i have to write which shall use these variable settings.
can anybody provide me suggestions to correct me where I am doing wrong?
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
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).
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With