在 Linux 中source脚本和执行脚本之间的区别
1. 概述
在 Linux 中,我们可以source 或执行 shell 脚本。这两个操作非常相似,但又有所不同。
在本快速教程中,我们将通过示例讨论它们的区别。
2. Sourcing 和 Executing 都会运行脚本中的命令
首先,获取和执行脚本都将运行目标脚本中的所有命令。一个简单的例子可以直截了当地展示它。
假设我们有一个 shell 脚本 myScript.sh:
$ cat myScript.sh
#!/bin/bash
echo "Hey, I'm a shell script file."
如上面的输出所示,脚本非常简单。它只包含一个 echo命令。
现在,让我们执行并获取这个脚本:
$ ./myScript.sh
Hey, I'm a shell script file.
$ source myScript.sh
Hey, I'm a shell script file.
我们可以看到,这两个操作都执行 了目标脚本中的echo命令。
接下来,让我们看另一个例子。
3. 扩展脚本并再次测试
首先,让我们通过添加一个变量和一个函数来扩展我们的 myScript.sh文件:
$ cat myScript.sh
#!/bin/bash
echo "Hey, I'm a shell script file."
COUNTRY="United States of America"
echo "Now, the variable \$COUNTRY=$COUNTRY"
greeting() {
echo "Hi $1, how are you doing?"
}
echo 'Say Hi to "Kent" by calling the function:'
greeting "Kent"
现在,我们已经在脚本中定义了COUNTRY变量和greeting函数。
接下来,让我们首先获取脚本:
$ source myScript.sh
Hey, I'm a shell script file.
Now, the variable $COUNTRY=United States of America
Say Hi to "Kent" by calling the function:
Hi Kent, how are you doing?
上面的例子表明我们有预期的输出。
获取文件后,让我们验证变量值并测试echo功能:
$ echo $COUNTRY
United States of America
$ greeting "Eric and Kevin"
Hi Eric and Kevin, how are you doing?
正如输出所示,到目前为止,一切都很好,一切都按预期工作。
接下来,让我们启动一个新的 shell 并执行 myScript.sh脚本:
$ ./myScript.sh
Hey, I'm a shell script file.
Now, the variable $COUNTRY=United States of America
Say Hi to "Kent" by calling the function:
Hi Kent, how are you doing?
同样,运行脚本会产生预期的输出。接下来,让我们执行相同的测试,验证变量并测试函数:
$ echo $COUNTRY
$ greeting "Eric and Kevin"
bash: greeting: command not found
这一次,正如我们所看到的,即使它在我们执行脚本时打印了预期的输出,echo $COUNTRY命令也不会打印任何内容。此外,当我们调用greeting函数时,我们得到了“ command not found ”错误。
似乎无法识别变量和函数。所以,让我们弄清楚它为什么会发生。
4. source和执行脚本的区别
当我们获取脚本时,该脚本在当前 shell 中执行。换句话说,如果我们在脚本中声明了新的变量和函数,那么在获取它之后,这些变量和函数在当前 shell 中也是有效的。这就是为什么在我们获取myScript.sh之后我们的测试产生了预期的结果 。
另一方面,**当我们执行一个脚本时,它会在一个新的 shell 中执行,它是当前 shell 的一个子 shell 。**因此,脚本创建的所有新变量和函数将只存在于子shell中。脚本完成后,子shell进程也终止。因此,变化消失了。
因此,在我们之前的测试中,执行 myScript.sh 后,$COUNTRY变量和 greeting函数在当前 shell 中不可用。