source exec 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 $1 in 
	exec)
		echo "using exec..."
		exec ./2.sh
		;;
	source)
		echo "using source..."
		. ./2.sh
		;;
	*)
		echo "using fork by default..."
		./2.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"

source测试


[root@fire Shell]# ./1.sh source
PID for 1.sh before exec/source/fork ; 8952
1.sh : $A is B
using source...
PID for 2.sh : 8952 
2.sh get $A=B from 1.sh
2.sh : $A is C
PID for 1.sh after exec/source/fork : 8952
1.sh : $A is C

对于参数 source,表示执行2脚本格式是:source 2.sh,由输出可以看出,source的执行就是在本shell中执行,共用原shell的环境变量

fork测试


[root@fire Shell]# ./1.sh 
PID for 1.sh before exec/source/fork ; 9019
1.sh : $A is B
using fork by default...
PID for 2.sh : 9020 
2.sh get $A=B from 1.sh
2.sh : $A is C
PID for 1.sh after exec/source/fork : 9019
1.sh : $A is B

对于普通的./xxx.sh,shell新建了一个子shell(sub-shell),sub-shell继承了父shell的环境变量,仅仅是copy版本而已,子shell里面无论怎么修改变量,在子shell退出之后,子shell的所有资源和变量都被回收。所以是不会影响父shell的。在子shell执行的时候,父shell会处于挂起状态,等待子shell结束返回。

exec测试


PID for 1.sh before exec/source/fork ; 9095
1.sh : $A is B
using exec...
PID for 2.sh : 9095 
2.sh get $A=B from 1.sh
2.sh : $A is C

对于exec也会让行程在同一个shell上执行,只是exec的调用会把原来的shell执行的行程结束了,重新开始另一个行程。

标签:Linux, Shell

评论已关闭