Updated 2011-03-19 16:52:38 by Cameron

"How do I set an environment variable from a script?" This question is

  • frequent,
  • imprecise,
  • generally impossible, but
  • interesting.

"Imprecise" here means that, as it stands, the question could mean several quite different things. Most typical is this: in a command-line environment, a user wants to invoke a small script which re-assigns environment variables. While the examples here refer to Tcl, exactly the same considerations and conclusions apply with other languages. The short answer is: you can't. For sound security reasons, child processes cannot modify a number of different characteristics of their parents, let alone independent processes; environment variables are among these protected characteristics.

However, there are a number of variations on this theme which have the potential to give all the satisfaction of an envvar-setting script. Tom Wilkason provides a recipe for setting envvar for new Windows sessions in "Setting /bin/sh environment variables in the script".

More important, and more broadly applicable, are several cooperative models from the early days of Unix. In these, a process asks for a change of envvar. For example, under Unix, a parent sh-interpreting process might invoke
  source `my_example.tcl`

If my_example.tcl contains
    #!/usr/bin/tclsh
    puts "export MY_VAR=some_value"

teamwork between the two processes will result in the parent receiving some_value in its MY_VAR environment variable. LV hints at other examples in "Setting /bin/sh environment variables in the script".

LV I'll be the first to admit that I'm tired - it's the end of a long day of a long week. But that example doesn't look quite right. It seems to me that what you would end up with is an attempt of sh to evaluate
  source "export MY_VAR=somevalue"

which it seems would be an unlikely file name to find. Perhaps you meant to use
  eval `my_example.tcl`

??

A specific requirement is sometimes to alter the environment that the Tcl process itself sees; this environment is also the one seen by child processes that the script creates with the exec command. This environment is exposed to the script via the array env. Use of env is discussed on the man page tclvars (see http://www.purl.org/tcl/home/man/tcl8.4/TclCmd/tclvars.htm for details). As pointed out above, these changes to the environment apply only to the Tcl script and its children, have no effect on the script's parent process.

Also see "Robust environment variables on Windows".

Also, see the Wikipedia entry on the topic [1] and ... [FAQ].

Category Tutorial (is there a better category than this?)