Unix: (pwd now: ~) from cd 命令?

Unix: (pwd now: ~) from cd command?

我就是我,我去玩终端机 (zsh)。我尝试过的其中一件事(在一个空目录中)是 mkdir test; ls | cd 这个 应该 创建一个文件夹,然后打印所有文件夹(只有那个文件夹)并将输出通过管道传输到 cd。所以我希望它能带我到测试目录,但我却得到了 (pwd now: ~) 并且它带我回到了主目录。有人知道为什么吗?查找它没有任何用处。

编辑:它将我带到 ~ 目录,因为 cd 不接受标准输入输入,而是该目录是一个参数。我仍然想知道的是为什么 运行 ls | cd 给出输出 (pwd now: ~) 而不是什么都没有。 运行 echo test | cd 没有输出但 ls | cd 有。

当您将一个进程或作业的输入“管道”到另一个进程或作业时,您同时也在生成另一个进程。据说这两个作业都是调用它们的主进程的“子进程”(通常是进程 运行 终端仿真器)。

# 2 process are run here
# first job: echo
# second job: ls
echo "/home/" | ls

查看 zsh, it looks like when the cwd of a job differs from the original cwd of the job after execution, it will notify the user with a message like (pwd now: foo). This helps to ensure that the user knows exactly where the are in the directory tree, which is especially useful when they may not have intended to do so. Below is taken from jobs.c 的来源,其中 cwd(称为 pwd)其中 cwd(称为 pwd) 在打印 (pwd now: foo) 消息之前进行比较。如果它们不同,则打印消息,如果它们相等,则不打印。

if ((lng & 4) || (interact && job == thisjob &&
              jn->pwd && strcmp(jn->pwd, pwd))) {
    doneprint = 1;
    fprintf(fout, "(pwd %s: ", (lng & 4) ? "" : "now");
    fprintdir(((lng & 4) && jn->pwd) ? jn->pwd : pwd, fout);
    fprintf(fout, ")\n");
    fflush(fout);
    }

当您将某些内容通过管道传输到 ch 时,您正在更改子进程中的 cwd,并且一些在直接调用 cd 时隐藏此消息的常规检查被双向传递。否则cd字同理

# changes directories into ./test
echo "test" | cd
# (pwd now: /path/to/test)

# changes directory to home
echo | cd
# (pwd now: /home/<username>)

# calling this again will not echo the message, since the cwd is already
# the home directory and no change occurs 
echo | cd

至于为什么 cwd 被更改为主目录 (~),这是由于 cd 在没有给出路径作为参数时的行为方式。与许多 linux 命令不同,cd 不会从 stdin 读取路径以进入。因此,管道进入 cd 将简单地为 cd 填充 stdin,但该内容将被忽略。因为这个进入 cd 的管道与单独调用 cd 是一样的。

# these next lines produce the same behavior
echo path/to/dir/test | cd
cd

cd 没有收到要移动到的路径时,它会将您移动到您的主目录(在 linux 系统上引用为 ~

# each of these lines produce the same behavior
cd /home/<username>
cd ~
cd