【问题标题】:Why is change dir (cd) not working in this mac script? [duplicate]为什么更改目录(cd)在这个 mac 脚本中不起作用? [复制]
【发布时间】:2018-01-19 03:30:15
【问题描述】:

我在一个名为 /Users/tcl/scripts/gotoroot 的文件中有这个脚本:

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

【问题讨论】:

    标签: bash


    【解决方案1】:

    当您运行脚本时,它会在一个新进程中启动一个子shell。 cd 更改该子外壳内的目录,而不是您的终端进程内。

    将其放入脚本中进行测试:

    pwd
    cd /
    pwd
    

    您应该会看到它在脚本中更改为/

    【讨论】:

    【解决方案2】:

    Shell 脚本在子进程内运行。 CD 正在工作,但它发生在与您的主终端会话不同的进程中,并且一旦您返回到您的终端会话,它对工作目录没有影响。

    【讨论】:

      猜你喜欢
      • 2010-09-20
      • 1970-01-01
      • 1970-01-01
      • 2018-10-25
      • 1970-01-01
      • 2015-06-16
      • 2020-12-14
      相关资源
      最近更新 更多