在shell脚本中设置环境变量不会使它对shell可见 [英] Setting environment variable in shell script does not make it visible to the shell

查看:166
本文介绍了在shell脚本中设置环境变量不会使它对shell可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用一个可以调用来设置一些环境变量的shell脚本。但是,执行脚本后,我在bash中看不到使用printenv的环境变量。



这是我的脚本:

 #!/ bin / bash 

echoHello!
export MYVAR = boubou
echo设置MYVAR!

当我做./test.sh时,我看到:

 您好! 
设置MYVAR!

当我做printenv MYVAR时,我什么也看不到。



你能告诉我我做错了什么吗?

解决方案

这就是环境变量的工作原理。每个过程都有一个环境的副本。进程对其副本的任何更改都会传播到进程的子级。然而,他们不会传播到进程的父母。



解决这个问题的一个方法是使用源代码命令:

 源./test.sh 

 



当您执行此操作时,而不是在子shell中运行该脚本, bash 将执行脚本中的每个命令,就像在提示。


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.

Here is my script:

#!/bin/bash

echo "Hello!"
export MYVAR=boubou
echo "After setting MYVAR!"

When I do "./test.sh", I see:

Hello!
After setting 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.

One way to get around this is by using the source command:

source ./test.sh

or

. ./test.sh

(the two forms are synonymous).

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆