Setting environment variables from within TCL script

24,479

Solution 1

In Tcl you have the global env array:

set ::env(foo) bar

And then any child process has the variable foo in its environment.

If you want to put environment variables in a central file (i.e. .bash_profile) so that other programs can source them, then it should be pretty easy to get Tcl to parse that file and set the variables in the env array.

Solution 2

Generally speaking (at least for Linux and Unix-like systems), it's not possible from within a child process to alter the environment of the parent. It's a frequently asked question about tcl

However, if you're launching some other software from within the Tcl script, you can do a couple of things, the simplest of which may be to create a shell script file which both sets environment variables and then launches your software. Then run the shell script from within Tcl.

Solution 3

The environment is exposed via the global env array in Tcl. The keys and values of the array default to the environment inherited from the parent process, any process that Tcl creates will inherit a copy of it, and code that examines the environment in the current process (including directly from C) will see the current state of it.

Picking up environment set in a shell script is quite tricky. The issue is that a .bashrc (for example) can do quite complex things as well as setting a bunch of environment variables. For example, it can also print out a message of the day, or conditionally take actions. But you can at least make a reasonable attempt by using the shell's env command:

set data [exec sh -c "source /path/to/file.sh.rc; env"]
# Now we parse with some regular expression magic
foreach {- key value} [regexp -all -inline {(?wi)^(\w+)=((?!')[^\n]+|'[^']+')$} $data] {
    set extracted_env($key) [string trim $value "'"]
}

It's pretty awful, and isn't quite right (there are things that could confuse it) but it's pretty close. The values will be populated in the extracted_env array by it.

I think it's easier to get people to configure things via Tcl scripts…

Share:
24,479
Attiq
Author by

Attiq

Updated on July 09, 2022

Comments

  • Attiq
    Attiq almost 2 years

    I was creating a Tcl script which will allow me to automate the installation of software. But the problem I am running into is that the software needs some environment variables set beforehand and I was wondering if its possible to set environment variables inside of the tcl script.

    I was going to try exec /bin/sh -c "source /path/to/.bash_profile but that would create a shell script and source the variables into there and the tcl script wont pick it up then.

    Can anyone give any other ideas?