0

I wrote a C program in Linux to set the values of environment variables using setenv, but I cannot set value for array variable (I printed the value of the array to an output file, but the content of the file is blank), but non-array variables are working fine. Here is the code snippet:

setenv("header", "Welcome: ", 1);             // work fine, can output to file
setenv("info[0]", "192.168.1.1: ", 1);        // nothing are shown in output file
setenv("info[1]", "AA-AA-AA-BB-BB-BB: ", 1);  // nothing are shown in output file

I cannot find any reason why it not work :( Any help is appreciated.

2
  • @unwind I think the question was about using C setenv(), not about bash Commented Oct 22, 2013 at 8:56
  • @pmod Yeah ... my point with the dupe was that "arrays are a Bash feature, they are not environment variables, even Bash cannot export them". Commented Oct 22, 2013 at 9:01

1 Answer 1

1

Arrays are handled by bash, they don't exist as environment variables. Environment variables are stored in kernel per process as VARNAME=value, you can check this:

$ cat /proc/$$/environ | tr '\0' '\n'

But you can use array in the form of string with delimiter (coma or tab sign or whatever):

info=192.168.1.1:,AA-AA-AA-BB-BB-BB:

and handle this string in appropriate way

Also you should be careful with its names. First of all there is specific requirements on how the name should be composed:

Environment variable names used by the utilities in the Shell and Utilities volume of IEEE Std 1003.1-2001 consist solely of uppercase letters, digits, and the '_' (underscore) from the characters defined in Portable Character Set and do not begin with a digit. Other characters may be permitted by an implementation; applications shall tolerate the presence of such names.

The second thing to note is that you risk to modify some variable some other component of program is relying on.

Sign up to request clarification or add additional context in comments.

3 Comments

I got your point now. I think I need to find another way; my array is rather big and storing all members in a string with delimiter may not be a good solution :-)
@silent82lion90 Temporary file or lightweight DB then?
It's an array containing the IP and MAC of all users currently connecting to my server, at maximum the array may contain some hundred members (about 500). Using temporary file may be fine I think, using DB is a little overkill for this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.