Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / 在Linux中用source,dot(.)和直接用脚本文件名执行shell脚本的区别

用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
123453,以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$