fork exec source的区别
参考:http://www.cnblogs.com/bkygg/p/5023072.html
1:fork 运行的时候开一个sub_shell 执行调用的脚本,sub_shell执行的时候,parent_shell还在。sub_shell执行完毕后返回parent_shell。sub_shell从parent_shell继承环境变量。但是sub_shell中的变量不会带回parent_shell。在子命令执行完后再执行父命令,子级的环境变量不会影响到父级
2:exec 执行子级的命令后,不再执行父级的后面的命令
3:source 执行子级命令后继续执行父级的命令,同时子级设置的环境变量会影响到父级的环境变量
与fork的区别是不新开一个sub_shell来执行被调用的脚本,而是在同一个shell中执行,所有被调用的脚本中的声明的变量和环境变量,都可以在主脚本中得到使用
例子理解:
1.sh
#!/bin/bash A=B #$$表示当前进程的PID 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......" 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"
执行的结果:
[root@lile shell]# ./1.sh fork PID for 1.sh before exec/source/fork:21852 1.sh: $A is B using fork by default...... PID for 2.sh:21853 2.sh get $A=B from 1.sh 2.sh:$A is C PID for 1.sh after exec/source/fork:21852 1.sh: $A is B
[root@lile shell]# ./1.sh source PID for 1.sh before exec/source/fork:21862 1.sh: $A is B using source...... PID for 2.sh:21862 2.sh get $A=B from 1.sh 2.sh:$A is C PID for 1.sh after exec/source/fork:21862 1.sh: $A is C
[root@lile shell]# ./1.sh exec PID for 1.sh before exec/source/fork:21863 1.sh: $A is B using exec...... PID for 2.sh:21863 2.sh get $A=B from 1.sh 2.sh:$A is C
作者:李先生
-------------------------------------------
个性签名:在平凡中坚持前行,总有一天会遇见不一样的自己!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!
万水千山总是情,打赏一分行不行,所以如果你心情还比较高兴,也是可以扫码打赏博主,哈哈哈(っ•̀ω•́)っ✎⁾⁾!
微信公众号 微信打赏 支付宝打赏
posted on 2016-09-28 20:16 Captain_Li 阅读(545) 评论(0) 编辑 收藏 举报