问题描述
最近,我写了一个脚本,设置环境变量,一起来看看:
Recently I wrote a script which sets an environment variable, take a look:
#!/bin/bash
echo "Pass a path:"
read path
echo $path
defaultPath=/home/$(whoami)/Desktop
if [ -n "$path" ]; then
export my_var=$path
else
echo "Path is empty! Exporting default path ..."
export my_var=$defaultPath
fi
echo "Exported path: $my_var"
它的工作原理只是伟大的,但问题是, my_var
可不仅仅是局部地区,我的意思是在控制台窗口,在这里我跑了剧本。
It works just great but the problem is that my_var
is available just locally, I mean in console window where I ran the script.
如何写一个脚本,让我出口的全球环境变量,到处都可以看到?
How to write a script which allow me to export global environment variable which can be seen everywhere?
推荐答案
每一个shell都有它自己的环境。有没有的通用的环境,会奇迹般地出现在所有的控制台窗口。在一个外壳创建的环境变量不能在另一个shell访问。
Each and every shell has its own environment. There's no Universal environment that will magically appear in all console windows. An environment variable created in one shell cannot be accessed in another shell.
它甚至更加严格。如果一个壳产生一个子shell,即子shell访问父的环境变量,但如果子shell创建一个环境变量,它不是在父shell访问。
It's even more restrictive. If one shell spawns a subshell, that subshell has access to the parent's environment variables, but if that subshell creates an environment variable, it's not accessible in the parent shell.
如果您所有的炮弹都需要访问相同的变量,你可以创建一个的启动的文件,将它们设置为你。这是在bash通过 $ HOME / .bash_profile中
和 $ HOME / .bashrc中
文件,并通过<$ C完成$ C> $ HOME / .profile文件如果 $ HOME / .bash_profile中
不存在)。其他炮弹有自己的一套的启动文件。一个用于登录,一个用于没有登录催生了炮弹。请参阅手册页,了解他们正在执行的正是启动脚本的使用和什么样的顺序)。
If all of your shells need access to the same set of variables, you can create a startup file that will set them for you. This is done in BASH via the $HOME/.bash_profile
and $HOME/.bashrc
files and through $HOME/.profile
if $HOME/.bash_profile
doesn't exist). Other shells have their own set of startup files. One is used for logins, and one is used for shells spawned without logins. See the manpage to learn exactly what startup scripts are used and what order they're executed).
您可以尝试使用共享内存,但我相信,只有当进程正在运行的工作,因此,即使你想出一个办法来设置了一块共享内存,那就只要该命令完成走开。 (我很少使用的共享内存命名管道除外)。否则,真的没有办法自动设置在一个外壳的环境变量,并有另一种外壳把它捡起来。您可以尝试使用或编写环境变量为其他shell文件把它捡起来。
You can try using shared memory, but I believe that only works while processes are running, so even if you figured out a way to set a piece of shared memory, it would go away as soon as that command is finished. (I've rarely used shared memory except for named pipes). Otherwise, there's really no way to set an environment variable in one shell and have another shell automatically pick it up. You can try using named pipes or writing that environment variable to a file for other shells to pick it up.
想象一下可能发生,如果有人可以改变一个shell环境我不知情的问题。
Imagine the problems that could happen if someone could change the environment of one shell without my knowledge.
这篇关于如何写一个bash脚本设置全局环境变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!