source 就是让 script 在当前 shell 内执行、而不是产生一个 sub-shell 来执行。由
exec 也是让 script 在同一个行程上执行,但是原有行程则被结束了。
source ./my.script
或: . ./my.script
也就是简而言之:原有行程会否终止,就是 exec 与 source/fork 的最大差异了。
代码1.sh
#!/bin/bash
A=B
echo "PID FOR 1.sh before exec/source/fork:$$"
export A
echo "1.sh:\$A is $A"
case $ in
exec)
echo "using exec,,,,,"
exec ./.sh ;; #执行完成后结束
source)
echo "using source...."
. ./.sh ;; #执行完成后继续执行
*)
echo "using fork by default...."
./.sh ;; #另起一个进程来执行 .sh 执行后继续执行1.sh
esac echo "PID FOR 1.sh after exec/source/fork :$$"
echo "1.sh:\$A is $A"
代码 2.sh
#!/bin/bash
echo "PID for 2.sh:$$"
echo "2.sh get \$A=$A from 1.sh"
A=C
export A
echo "2.sh: \$A is $A"
修改文件权限:
chmod .sh
chmod .sh
测试代码:
$ ./.sh fork
$ ./.sh source
$ ./.sh exec
结果:
# ./.sh exec
PID FOR .sh before exec/source/fork:
.sh:$A is B
using exec,,,,,
PID for .sh:
.sh get $A=B from .sh
.sh: $A is C # ./.sh source
PID FOR .sh before exec/source/fork:
.sh:$A is B
using source....
PID for .sh:
.sh get $A=B from .sh
.sh: $A is C
PID FOR .sh after exec/source/fork :
.sh:$A is C # ./.sh fork
PID FOR .sh before exec/source/fork:
.sh:$A is B
using fork by default....
PID for .sh:
.sh get $A=B from .sh
.sh: $A is C
PID FOR .sh after exec/source/fork :
.sh:$A is B