在 shell 脚本中设置环境变量不会使其对 shell 可见 [英] Setting environment variable in shell script does not make it visible to the shell
问题描述
我想使用一个可以调用的 shell 脚本来设置一些环境变量.但是,执行脚本后,我在 bash 中没有看到使用printenv"的环境变量.
I want to use a shell script that I can call to set some environment variables. However, after the execution of the script, I don't see the environment variable using "printenv" in bash.
这是我的脚本:
#!/bin/bash
echo "Hello!"
export MYVAR=boubou
echo "After setting MYVAR!"
当我执行./test.sh"时,我看到了:
When I do "./test.sh", I see:
Hello!
After setting MYVAR!
当我执行printenv MYVAR"时,我什么也看不到.
When I do "printenv MYVAR", I see nothing.
你能告诉我我做错了什么吗?
Can you tell me what I'm doing wrong?
推荐答案
这就是环境变量的工作方式.每个进程都有一个环境副本.进程对其副本所做的任何更改都会传播到进程的子进程.但是,它们不会传播到进程的父进程.
This is how environment variables work. Every process has a copy of the environment. Any changes that the process makes to its copy propagate to the process's children. They do not, however, propagate to the process's parent.
解决此问题的一种方法是使用 source
命令:
One way to get around this is by using the source
command:
source ./test.sh
或
. ./test.sh
(这两种形式是同义词).
(the two forms are synonymous).
执行此操作时,bash
将执行脚本中的每个命令,就像在提示符下键入一样,而不是在子 shell 中运行脚本.
When you do this, instead of running the script in a sub-shell, bash
will execute each command in the script as if it were typed at the prompt.
这篇关于在 shell 脚本中设置环境变量不会使其对 shell 可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!