关于tclsh 中环境变量(env)的使用

来源:互联网 发布:高考状元笔记淘宝 编辑:程序博客网 时间:2024/06/07 20:57

有一个脚本调用:shell script 调用tcl script

shell script -> tclsh


这里shell脚本执行时有很多环境变量,在tclsh如何获取?

其实tclsh已经很好地继承了调用它的shell 脚本中的环境变量:

global 的变量env,其实是一个数组:

% parray env
env(DISPLAY)            = localhost:10.0
env(HOME)               = /home/windriver
env(LANG)               = en_US.UTF-8
env(LESSCLOSE)          = /usr/bin/lesspipe %s %s
env(LESSOPEN)           = | /usr/bin/lesspipe %s
env(LOGNAME)            = windriver
env(PWD)                = /home/windriver
env(SHELL)              = /bin/bash
env(_)                  = /usr/bin/tclsh


如果在tcl脚本中修改了env 中某个环境变量,tclsh 脚本中的相应的环境变量也随之改变,如果在tclsh 中调用了别的脚本或者exec 命令,则sub-process会继承tclsh脚本中的环境变量。


曾经试图通过tclsh脚本去修改shell 脚本中的env 环境变量,因为这个shell脚本会使用环境变量去调用其他的脚本,想让这个环境变量在tclsh 脚本中被更改并传递给shell 脚本。

使用了以下方法:

set env(MY_VAR)  Modification.

或者

exec sh -c "export MY_VAR=IModifiedThis!"

但实践表明:不能从sub-process 中去修改parent process中的环境变量。


从tcl/tk 官方得到一些信息(http://www2.tcl.tk/706):

 Many times people come looking for a way to set an environment variable in such a way as to influence a parent process. This is, in generally, rather difficult to do. One generally solves this problem via cooperation - in some way communicating back to the parent process that it needs to set the variable itself.

For example, you could write out to stdout the value you want the parent to get, then have the parent process read the child's stdout and put the value into the variable.

Or you could write out a text file containing variable names and values (perhaps in shell format) then have the parent read in the values and take the action. Or you could set up some sort of socket, pipe, etc. and communciate that way.

But at least in Unix like systems, a child process DOES NOT HAVE WRITE ACCESS to the process space of the parent. Period .

CL puts it more starkly: "... you can't change the value of an environment variable in another already running process", according to the authoritative Unix Programming FAQ [1] (why? Among other reasons, security considerations prohibit such an operation). However, as Larry hints above, there are ways to change the question slightly to give effective control over ...

See "Setting environment variables with a script" for more.