現象:腳本 a.sh 含 cd /,執行 bash a.sh 雖輸出 /,但結束後工作目錄未變。
執行腳本會 fork 子進程,cd 僅影響子進程環境,父 Shell (終端機) 不受影響。
source a.sh:在當前 Shell 解讀執行,環境變更保留. ./a.sh (點命令):. 為 Bash 內建命令,意義同 source,./a.sh 為路徑,中間必須有空格[fedora@localhost ~]$ . ./a.sh
/
complete
[fedora@localhost /]$
掌握此機制,避免「腳本改目錄不生效」的常見誤區。