歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> 在Linux中用source,dot(.)和直接用腳本文件名執行shell腳本的區別

在Linux中用source,dot(.)和直接用腳本文件名執行shell腳本的區別

日期:2017/3/1 10:17:30   编辑: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
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$
Copyright © Linux教程網 All Rights Reserved