腳本裡 cd 成功,終端機卻沒移動?看懂 Bash 的工作目錄 / Why cd in a Script Does Not Move Your Terminal
目錄怎麼又回去了? / Why did the directory revert? 假設你在 Linux 的 Bash 終端機裡執行一支腳本,裡面明明寫了切換目錄,腳本也沒有報錯,結束後卻還停在原處。這通常不是路徑失靈,而是你把「另一個 shell 的工作目錄」,當成了眼前這個 shell 的狀態。 Imagine running a script in a Bash terminal on Linux. The script changes directory without an error, yet your terminal remains where it started. Usually the path is not broken: you have mistaken another shell’s working directory for the state of your current shell. 工作目錄是程序用來解讀相對路徑的起點,不是整台電腦共用的一個游標。以 bash go.sh 執行腳本時,新的 Bash 會繼承起始目錄;它之後呼叫 cd,只改變自己的工作目錄,並不把變更回寫給啟動它的 shell。[1] The working directory is a process’s starting point for resolving relative paths, not a computer-wide cursor. Running bash go.sh starts another Bash that inherits the initial directory. Its subsequent cd changes its own working directory, without writing that change back to the shell that launched it. [1] 圖一|繼承不等於回寫:腳本結束,外層仍在原處。原創示意圖,非產品或實測截圖。 / Figure 1 | Inheritance is not write-back: the outer shell stays put after the script exits. Original diagram, not a product ...