我有两个文件file1和file2。在file1中,我声明了一个var x=1。在文件2中,我让变量x=2。如果我先运行文件1,然后再运行文件2,然后在shell echo x中,得到x=2。当我需要的时候,我如何从file1访问x=1,然后如果我需要的话,我如何从file1访问x=2。
如果从file中调用file2,则希望在file1中导出x它应该是这样的:
file1.sh
#!/bin/bash
export x=1
echo "$x from $0"
./file2.sh
echo "$x from $0"
file2.sh
#!/bin/bash
x=2
echo "$x from $0"
输出将是
$ ./file1.sh
1 from ./file1.sh
2 from ./file2.sh
1 from ./file1.sh
$
如果分别调用file1.sh和file2.sh,则x必须在file1.sh执行之前声明。
在这个例子中x是未定义的,然后它被导出为一个全局变量,你可以从第二次回显中看到它的值:
$ echo $x
$ export x=1
$ echo $x
1
$
如果从file1.sh中删除包含x声明和调用file2.sh的行,那么您将看到file1.sh继承了x的值。但是它在file2.sh中被覆盖了。
一旦file2.sh执行完成,x的值仍然是1:
$ ./file1.sh
1 from ./file1.sh
$ ./file2.sh
2 from ./file2.sh
$ echo $x
1
$
您可以尝试在shell中导出x=3,并使用file1.sh和file2.sh,如第一个示例所示,然后您将看到如下内容:
$ export x=3; echo $x; ./file1.sh ; echo $x
3
1 from ./file1.sh
2 from ./file2.sh
1 from ./file1.sh
3
$
对
在file2.sh中,您可以将其写成: ${x=2}
而不是x=2
。
——演示
# Creating the files
$ echo x=1 > file1.sh
$ echo ': ${x=2}' > file2.sh
# Running both files
$ . file1.sh
$ . file2.sh
$ echo $x
1
# See? the output is 1, which was set by file1.sh
# Now, if you want to get the value of x from file2.sh -
$ unset -v x
$ . file2.sh
$ echo $x
2
# See? the output is 2, which was set by file2.sh
$ . file1.sh
$ echo $x
1
# See? x was over-written by file1.sh
上面demo中file1.sh的内容-
x=1
上面demo中file2.sh的内容
: ${x=2}