Shell 中 Source 和 Exec 的区别

2017/06/03

粗略地看,sourceexec 都是读取一个脚本文件并执行其内容,而它们的不同点在于,source 是在当前 shell 中执行读取到的命令,而 exec 是产生一个 sub-sehll 来*顶替*现有 shell,因此原脚本中 exec 语句后面的内容不会执行,同时 shell 的环境也改变了,然而进程的 pid 值却不会改变。

E.g.

创建三个文件,分别命名为 source.shexec.shsub.sh,写入如下内容:

#!/bin/bash
echo "This is source."
source sub.sh
echo "Still get run."
#!/bin/bash
echo "This is exec."
exec ./sub.sh
echo "This is killed and doesn't get run."
#!/bin/bash
echo "This is the sub.sh being called."

运行结果

$ ./source.sh
This is source.
This is the sub.sh being called.
Still get run.

$ ./exec.sh
This is exec.
This is the sub.sh being called.

原博说的详细多了,我这里只是把一些对我来说比较重要的点总结一下。