Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash: set array env variable and de-referencing it from any shell script fails

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?

like image 480
OpenFile Avatar asked Dec 31 '12 10:12

OpenFile


3 Answers

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
like image 54
ormaaj Avatar answered Nov 07 '22 02:11

ormaaj


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).

like image 38
cdarke Avatar answered Nov 07 '22 04:11

cdarke


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).

like image 39
Toby Speight Avatar answered Nov 07 '22 03:11

Toby Speight