如何从脚本设置 bash 环境变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3065067/
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 do I set bash environment variables from a script?
提问by James A. Rosen
I have some proxy settings that I only occasionally want to turn on, so I don't want to put them in my ~/.bash_profile. I tried putting them directly in ~/bin/set_proxy_env.sh, adding ~/binto my PATH, and chmod +xing the script but though the script runs, the variables don't stick in my shell. Does anyone know how to get them to stick around for the rest of the shell session?
我有一些代理设置,我只是偶尔想打开,所以我不想把它们放在我的~/.bash_profile. 我尝试将它们直接放入~/bin/set_proxy_env.sh, 添加~/bin到我的PATH, 和chmod +xing 脚本,但尽管脚本运行,但变量不会粘在我的 shell 中。有谁知道如何让他们在 shell 会话的其余部分坚持下去?
回答by mob
Use one of:
使用以下之一:
source <file>
. <file>
回答by Amardeep AC9MF
In the script use
在脚本中使用
export varname=value
export varname=value
and also execute the script with:
并使用以下命令执行脚本:
source set_proxy_env.sh.
source set_proxy_env.sh.
The exportkeyword ensures the variable is marked for automatic inclusion in the environment of subsequently executed commands. Using sourceto execute a script starts it with the present shell instead of launching a temporary one for the script.
的export关键字确保该变量被标记为自动列入随后执行的命令的环境。使用source执行脚本本外壳,而不是推出一个临时的脚本启动它。
回答by Vivin Paliath
Did you try this:
你试过这个吗:
. ~/bin/set_proxy_env.sh
. ~/bin/set_proxy_env.sh
Running it by itself opens a separate subshell (I think) and sets the variable there. But then the binding is lost after exiting back into your shell. The dot at the front tells it to run it within the same shell.
单独运行它会打开一个单独的子shell(我认为)并在那里设置变量。但是,在退出回您的 shell 后,绑定就会丢失。前面的点告诉它在同一个 shell 中运行它。
Also, don't forget to exportthe variables you need like so: export MYVAR=value
另外,不要忘记export您需要的变量,如下所示:export MYVAR=value

