2017-08-10 46 views
0

我有一個名爲/用戶/ TCL /腳本/ gotoroot文件這個腳本:爲什麼更改目錄(cd)不能在此mac腳本中工作?

echo "hello" 
cd/
echo "good bye" 

但是當我運行它,我得到這個:

User:scripts tcl$ pwd 
/Users/tcl/scripts 
User:scripts tcl$ gotoroot 
hello 
good bye 
User:scripts tcl$ pwd 
/Users/tcl/scripts 
User:scripts tcl$ 

的目錄並沒有改變,我不不知道爲什麼?它應該是/,而不是/ Users/tcl/scripts

回答

5

當您運行腳本時,它會在新進程中啓動子shell。 cd更改該子shell中的目錄,而不是在終端進程中。

測試它通過把這個在你的腳本:

echo $(pwd) 
cd/
echo $(pwd) 

您應該看到它更改爲/在腳本中。

+1

明白了,謝謝。這是https://stackoverflow.com/questions/255414/why-doesnt-cd-work-in-a-bash-shell-script的副本。 – John

+0

爲什麼不只是'echo'$ PWD「'並跳過額外的過程? –

+0

@EricRenouf正確的瑣事將是「爲什麼不只是'pwd'並跳過回聲呢?」但你的也沒關係。 ;) –

1

Shell腳本在子進程中運行。 CD正在工作,但它發生在與主終端會話不同的進程內,並且在您返回到終端會話後對工作目錄沒有影響。

相關問題