Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1053849
  • 博文数量: 139
  • 博客积分: 1823
  • 博客等级: 上尉
  • 技术积分: 3403
  • 用 户 组: 普通用户
  • 注册时间: 2011-06-05 09:54
文章存档

2014年(7)

2013年(16)

2012年(48)

2011年(68)

分类: 系统运维

2011-08-28 12:42:56

  • fork  ( /directory/script.sh)

fork是最普通的, 就是直接在脚本里面用/directory/script.sh来调用script.sh这个脚本.

运行的时候开一个sub-shell执行调用的脚本,sub-shell执行的时候, parent-shell还在。

sub-shell执行完毕后返回parent-shell. sub-shell从parent-shell继承环境变量.但是sub-shell中的环境变量不会带回parent-shell

  • exec (exec /directory/script.sh)

exec与fork不同,不需要新开一个sub-shell来执行被调用的脚本.  被调用的脚本与父脚本在同一个shell内执行。但是使用exec调用一个新脚本以后, 父脚本中exec行之后的内容就不会再执行了。这是exec和source的区别

  • source (source /directory/script.sh)

与fork的区别是不新开一个sub-shell来执行被调用的脚本,而是在同一个shell中执行. 所以被调用的脚本中声明的变量和环境变量, 都可以在主脚本中得到和使用.


可以通过下面这两个脚本来体会三种调用方式的不同:

1.sh 

  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.sh 

  1.    1. #!/bin/bash
  2.    2. echo "PID for 2.sh: $$"
  3.    3. echo "2.sh get \$A=$A from 1.sh"
  4.    4. A=C
  5.    5. export A
  6.    6. echo "2.sh: \$A is $A"

 

 

执行情况:

  1. $ ./1.sh
  2. PID for 1.sh before exec/source/fork:5845364
  3. 1.sh: $A is B
  4. using fork by default…
  5. PID for 2.sh: 5242940
  6. 2.sh get $A=B from 1.sh
  7. 2.sh: $A is C
  8. PID for 1.sh after exec/source/fork:5845364
  9. 1.sh: $A is B
  10. $ ./1.sh exec
  11. PID for 1.sh before exec/source/fork:5562668
  12. 1.sh: $A is B
  13. using exec…
  14. PID for 2.sh: 5562668
  15. 2.sh get $A=B from 1.sh
  16. 2.sh: $A is C
  17. $ ./1.sh source
  18. PID for 1.sh before exec/source/fork:5156894
  19. 1.sh: $A is B
  20. using source…
  21. PID for 2.sh: 5156894
  22. 2.sh get $A=B from 1.sh
  23. 2.sh: $A is C
  24. PID for 1.sh after exec/source/fork:5156894
  25. 1.sh: $A is C
  26. $

阅读(1287) | 评论(0) | 转发(0) |
0

上一篇:Shell编程基础

下一篇:Shell脚本调试技术

给主人留下些什么吧!~~