Setting environment variables from TCL script

I created a Tcl script that will allow me to automate the software installation. But the problem I am facing is that the software requires some environment variables set in advance, and I was wondering if it is possible to set the environment variables inside 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 inject variables there, and tcl script would not be able to pick it up.

Can anyone give any other ideas?

+5
source share
3 answers

In Tcl, you have a global env array:

 set ::env(foo) bar 

And then any child process has a 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 run them, then it would be pretty easy to get Tcl to parse this file and set the variables to an env array.

+3
source

Generally speaking (at least for Linux and Unix-like systems), it is not possible to change the parent environment due to the child process. This is a frequently asked question about tcl

However, if you run any other software from a Tcl script, you can do a couple of things, the easiest of which can be to create a shell script file that sets both environment variables and runs your software. Then run the shell script from Tcl.

+3
source

The environment is mapped through the global env array in Tcl. The keys and default values โ€‹โ€‹of the array for the environment inherited from the parent process, any process that creates Tcl will inherit a copy of it, and code that examines the environment in the current process (including directly from C) will see its current state.

Choosing the environment installed in the shell script is quite complicated. The problem is that .bashrc (for example) can do quite complex things, as well as set many environment variables. For example, it can also print a message of the day or conditionally take action. But you can at least make a sensible attempt using the shell 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 "'"] } 

This is pretty awful and not quite right (there are things that can confuse him), but it's pretty close. Values โ€‹โ€‹will be populated in the extracted_env array.

I find it easier to get people to set things up with Tcl scripts ...

0
source

All Articles