bash 如何将 shell 变量导出到所有会话?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14991313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to export a shell variable to all sessions?
提问by user1293997
I would like to know is there a way to export my shell variable to all sessions in the system (not only the current session). I'm not looking to set it in .bashrc file as the shell variable is a dynamic one it changes time to time.
我想知道有没有办法将我的 shell 变量导出到系统中的所有会话(不仅是当前会话)。我不想在 .bashrc 文件中设置它,因为 shell 变量是一个动态变量,它会不时更改。
回答by that other guy
You can set up your sessions to keep rereading a file on disk by setting a trap on DEBUG in your .bashrc:
您可以通过在您的 DEBUG 上设置陷阱来设置会话以继续重新读取磁盘上的文件.bashrc:
trap 'source ~/.myvars' DEBUG
If you leave a terminal A open, run echo VAR=42 >> ~/.myvarsin terminal B, then switch back to terminal A and echo $VAR, it'll "magically" be set.
如果您将终端 A 保持打开状态,echo VAR=42 >> ~/.myvars在终端 B 中运行,然后切换回终端 A 并echo $VAR“神奇地”设置它。
回答by cdarke
You seem to misunderstand what exportdoes. All it does is to move a local variable into the environment block within the process (/proc/$$/environ).
你似乎误解了什么export。它所做的只是将局部变量移动到进程 ( /proc/$$/environ)内的环境块中。
When a new process is created (a fork) then the program data areas, including the environment block, are copied to the new process (actually they are initially shared, then copied when one writes). When a different programis run (execve), by default the environment block remains from the previous program. See also the env(1)program.
当一个新进程被创建时 (a fork) 然后程序数据区,包括环境块,被复制到新进程(实际上它们最初是共享的,然后在写入时复制)。当运行不同的程序(execve) 时,默认情况下,环境块保留在前一个程序中。另请参阅env(1)程序。
So environment variables are normally inherited (copied) from their parent process. The only way to get a new environmnt variable into a running process is to use some sort of inoculation technique, as a debugger would do. Writing such a program is not an easy task, and I'm sure you could imagine the security implications.
所以环境变量通常是从它们的父进程继承(复制)的。将新环境变量引入正在运行的进程的唯一方法是使用某种接种技术,就像调试器所做的那样。编写这样的程序并非易事,我相信您可以想象其中的安全隐患。

