导出在我的 shell 脚本中无法工作

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

Sh 如下:

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

Sh 如下:

#!/bin/sh
echo $variable

根据我读到的内容,这样做(导出)可以从一个 shell 脚本访问另一个 shell 脚本中的变量。但这在我的剧本里行不通。有人能帮帮我吗。先谢谢你。

87799 次浏览

export puts 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

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

and

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

to see the effect of export.

To get the variable from 1.sh to 2.sh, either call 2.sh from 1.sh, or import 1.sh in 2.sh:

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

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

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

. 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."