Linux 导出在我的 shell 脚本中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10781824/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 06:32:35  来源:igfitidea点击:

export not working in my shell script

linuxshellvariablesterminal

提问by Xander

I have two scripts 1.sh and 2.sh.

我有两个脚本 1.sh 和 2.sh。

1.sh is as follows:

1.sh如下:

#!/bin/sh
variable="thisisit"
export variable

2.sh is as follows:

2.sh如下:

#!/bin/sh
echo $variable

According to what I read, doing like this (export) can access the variables in one shell script from another. But this is not working in my scripts. Can somebody please help. Thanks in advance.

根据我读到的内容,这样做(导出)可以从另一个 shell 脚本访问一个 shell 脚本中的变量。但这在我的脚本中不起作用。有人可以帮忙吗。提前致谢。

回答by Fred Foo

exportputs a variable in the executing shell's environment so it is passed to processes executed by the script, but not to the process calling the script or any other processes. Try executing

export在执行 shell 的环境中放置一个变量,以便将其传递给由脚本执行的进程,但不会传递给调用脚本的进程或任何其他进程。尝试执行

#!/bin/sh
FOO=bar
env | grep '^FOO='

and

#!/bin/sh
FOO=bar
export FOO
env | grep '^FOO='

to see the effect of export.

来看看效果export

To get the variable from 1.shto 2.sh, either call 2.shfrom 1.sh, or import 1.shin 2.sh:

为了充分利用变1.sh2.sh,或者调用2.sh1.sh或进口1.sh2.sh

#!/bin/sh
. ./1.sh
echo $variable

回答by linuxeasy

If you are executing your files like sh 1.shor ./1.shThen you are executing it in a sub-shell.

如果您正在执行您的文件,例如sh 1.sh./1.sh那么您是在子 shell 中执行它。

If you want the changes to be made in your current shell, you could do:

如果您希望在当前 shell 中进行更改,您可以执行以下操作:

. 1.sh
# OR
source 1.sh

Please consider going through the reference-documentation.

请考虑阅读参考文档

"When a script is run using source[or .] it runs within the existing shell, any variables created or modified by the script will remain available after the script completes. In contrast if the script is run just as filename, then a separate subshell (with a completely separate set of variables) would be spawned to run the script."

“当使用source[或.] 运行脚本时,它在现有 shell 中运行,脚本创建或修改的任何变量在脚本完成后仍将保持可用。相反,如果脚本filename以完全独立的变量集)将被生成来运行脚本。”