首先進入shell目錄創(chuàng)建一個創(chuàng)建一個簡單的腳本echo.sh
$cd ~/shell
$vi echo .sh
#!/bin/bash
cd /tmp
echo "hello world"
1.賦予腳本可執(zhí)行權(quán)限,直接執(zhí)行
$pwd
~/shell
$chmod +x echo.sh
$./echo.sh
hello world
$pwd
~/shell
2.使用解釋器解釋并執(zhí)行該腳本
$pwd
~/shell
$chmod -x echo.sh
$/bin/bash echo.sh
hello world
$pwd
~/shell
3.使用source命令解釋并執(zhí)行該腳本
$pwd
~/shell
$chmod -x echo.sh
$source echo.sh
hello world
$pwd
/tmp
分析:發(fā)現(xiàn)第1,2中和第三種的區(qū)別在于前兩種運行完后所在目錄是~/shell,而第三種是/tmp秘通。是什么原因呢?原來linux每啟動一個終端都會為此終端開辟一個進程班缎,假設(shè)當前的終端進程為P進程寓娩,當我們只想前兩種方法時,p進程會fork一個子進程(假設(shè)為C進程)堕仔,然后在C進程中運行echo腳本擂橘,C進程和P進程剛開始有一樣的執(zhí)行環(huán)境,也就是當前目錄是~/shell摩骨,執(zhí)行完echo.sh后C進程的當前目錄會變成/tmp通贞,然后執(zhí)行echo "hello world",執(zhí)行完該腳本C進程會銷毀掉然后返回P進程恼五,但是P進程的當前目錄還是~/shell昌罩;source命令就不一樣了,source命令會讓P進程自己解釋并執(zhí)行echo.sh灾馒,所以執(zhí)行完之后當前目錄就是/tmp了茎用。
阿里云雙十一云服務(wù)器拼團活動,已經(jīng)打到最低價99元一年睬罗!有需要的可以考慮一波了轨功!
https://m.aliyun.com/act/team1111/#/share?params=N.9g4CZ2TwSh.qilw7y0a