用source,dot(.)的方式执行shell脚本的时候,不产生子进程,shell脚本在当前的shell中运行,shell脚本运行完成后,在shell脚本中声明的变量在当前的shell中是可见的.
直接用脚本文件名的方式执行shell脚本的时候,产生子进程,shell脚本在子进程中运行,shell脚本运行完成后,在shell脚本中声明的变量在当前的shell中是不可见的.
验证过程:
在当前目录下有一个tt.sh的脚本内容如下:
echo $$
ttvar=12345
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.
- test@ www.linuxidc.com :~/c$ echo $$
- 28210
- test@ www.linuxidc.com :~/c$ echo $$
- 28210
- test@ www.linuxidc.com :~/c$ sh
- sh-3.2$ echo $$
- 29152
- sh-3.2$ bash
- bash interactive changed
- test@ www.linuxidc.com :~/c$ echo $$
- 29153
- test@ www.linuxidc.com :~/c$ ps
- PID TTY TIME CMD
- 28210 pts/1 00:00:00 bash
- 29152 pts/1 00:00:00 sh
- 29153 pts/1 00:00:00 bash
- 29205 pts/1 00:00:00 ps
- test@ www.linuxidc.com :~/c$ exit
- exit
- sh-3.2$ echo $$
- 29152
- sh-3.2$ exit
- exit
- test@ www.linuxidc.com :~/c$ echo $$
- 28210
- test@ www.linuxidc.com :~/c$