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

本文探讨了Shell脚本调用Tcl脚本时环境变量的传递方式,并介绍了Tcl脚本如何获取这些环境变量。同时,文章还讨论了在Tcl脚本中修改环境变量的可能性及其限制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有一个脚本调用: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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值