原文连接:http://blog.chinaunix.net/uid-22548820-id-3181798.htmlhtml
fork是最普通的, 就是直接在脚本里面用/directory/script.sh来调用script.sh这个脚本。运行的时候开一个sub-shell执行调用的脚本,sub-shell执行的时候, parent-shell还在。shell
sub-shell执行完毕后返回parent-shell. sub-shell从parent-shell继承环境变量.可是sub-shell中的环境变量不会带回parent-shellbash
exec与fork不一样,不须要新开一个sub-shell来执行被调用的脚本. 被调用的脚本与父脚本在同一个shell内执行。可是使用exec调用一个新脚本之后, 父脚本中exec行以后的内容就不会再执行了。这是exec和source的区别ui
与fork的区别是不新开一个sub-shell来执行被调用的脚本,而是在同一个shell中执行. 因此被调用的脚本中声明的变量和环境变量, 均可以在主脚本中获得和使用.spa
能够经过下面这两个脚原本体会三种调用方式的不一样:.net
1.shunix
1 #!/bin/bash 2 A=B 3 echo "PID for 1.sh before exec/source/fork:$$" 4 export A 5 echo "1.sh: \$A is $A" 6 case $1 in 7 exec) 8 echo "using exec…" 9 exec ./2.sh ; 10 source) 11 echo "using source…" 12 . ./2.sh ; 13 *) 14 echo "using fork by default…" 15 ./2.sh ; 16 esac 17 echo "PID for 1.sh after exec/source/fork:$$" 18 echo "1.sh: \$A is $A"
2.shcode
1 #!/bin/bash 2 echo "PID for 2.sh: $$" 3 echo "2.sh get \$A=$A from 1.sh" 4 A=C 5 export A 6 echo "2.sh: \$A is $A"
执行状况:htm
$ ./1.sh PID for 1.sh before exec/source/fork:5845364 1.sh: $A is B using fork by default… PID for 2.sh: 5242940 2.sh get $A=B from 1.sh 2.sh: $A is C PID for 1.sh after exec/source/fork:5845364 1.sh: $A is B $ ./1.sh exec PID for 1.sh before exec/source/fork:5562668 1.sh: $A is B using exec… PID for 2.sh: 5562668 2.sh get $A=B from 1.sh 2.sh: $A is C $ ./1.sh source PID for 1.sh before exec/source/fork:5156894 1.sh: $A is B using source… PID for 2.sh: 5156894 2.sh get $A=B from 1.sh 2.sh: $A is C PID for 1.sh after exec/source/fork:5156894 1.sh: $A is C $