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

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

验证过程:

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

echo $$
ttvar=12345

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$