手机版
你好,游客 登录 注册
背景:
阅读新闻

在Linux中用source,dot(.)和直接用脚本文件名执行shell脚本的区别

[日期:2012-07-10] 来源:Linux社区  作者:kkdelta [字体:大 中 小]

用source,dot(.)的方式执行shell脚本的时候,不产生子进程,shell脚本在当前的shell中运行,shell脚本运行完成后,在shell脚本中声明的变量在当前的shell中是可见的.

直接用脚本文件名的方式执行shell脚本的时候,产生子进程,shell脚本在子进程中运行,shell脚本运行完成后,在shell脚本中声明的变量在当前的shell中是不可见的.

验证过程:

在当前目录下有一个tt.sh的脚本内容如下:

echo $$
ttvar=12345

1,先来看当前的shell的pid:28210
test@ www.linuxidc.com :~/c$ echo $$
28210
2,以source的方式执行tt.sh,脚本打印的pid和当前shell的pid一致,在tt.sh中定义的变量ttvar在脚本执行完成后仍然可以访问.

test@ www.linuxidc.com :~/c$ source tt.sh
28210
test@ www.linuxidc.com :~/c$ echo $ttvar
12345

3,以dot方式执行和source效果一样,先用unset将ttvar变量清除.
test@ www.linuxidc.com :~/c$ unset ttvar
test@ www.linuxidc.com :~/c$ echo $ttvar

test@ www.linuxidc.com :~/c$ . tt.sh
28210
test@ www.linuxidc.com :~/c$ echo $ttvar
12345
4以脚本文件名称直接运行,要件当前文件夹加入PATH,(或者以./tt.sh指定文件名)

test@ www.linuxidc.com :~/c$ PATH=$PATH:.
test@ www.linuxidc.com :~/c$ unset ttvar
test@ www.linuxidc.com :~/c$ echo $ttvar

test@ www.linuxidc.com :~/c$ tt.sh
28796
test@ www.linuxidc.com :~/c$ echo $ttvar

test@ www.linuxidc.com :~/c$
可以看到这种方式,产生了新的子进程,脚本运行完成后,里面定义的变量对于当前的shell是不可访问的.
在改变sh的时候也是要产生子进程的,通过exit退回到改变之前的sh.
  1. test@ www.linuxidc.com :~/c$ echo $$  
  2. 28210  
  3. test@ www.linuxidc.com :~/c$ echo $$  
  4. 28210  
  5. test@ www.linuxidc.com :~/c$ sh  
  6. sh-3.2$ echo $$  
  7. 29152  
  8. sh-3.2$ bash  
  9. bash interactive changed  
  10. test@ www.linuxidc.com :~/c$ echo $$  
  11. 29153  
  12. test@ www.linuxidc.com :~/c$ ps  
  13.   PID TTY          TIME CMD  
  14. 28210 pts/1    00:00:00 bash  
  15. 29152 pts/1    00:00:00 sh  
  16. 29153 pts/1    00:00:00 bash  
  17. 29205 pts/1    00:00:00 ps  
  18. test@ www.linuxidc.com :~/c$ exit  
  19. exit  
  20. sh-3.2$ echo $$  
  21. 29152  
  22. sh-3.2$ exit  
  23. exit  
  24. test@ www.linuxidc.com :~/c$ echo $$  
  25. 28210  
  26. test@ www.linuxidc.com :~/c$  
linux
相关资讯       shell 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款