重定向输出时 cd 不起作用?

发布于 2024-07-11 20:20:17 字数 501 浏览 7 评论 0原文

这是一个谜题:谁能解释为什么当输出重定向到管道时 cd 会失败?

例如:

james@machine:~$ cd /tmp                          # fine, no problem
james@machine:~$ cd /tmp | grep 'foo'             # doesn't work
james@machine:~$ cd /tmp | tee -a output.log      # doesn't work
james@machine:~$ cd /tmp >out.log                 # does work

在 OSX、Ubuntu 和 RHEL 上经过验证。

有任何想法吗?

编辑:我正在通过管道传输cd的输出,这看起来很奇怪? 原因是它来自一个用日志条目包装任意 shell 命令并处理输出的函数。

Here's a puzzler: can anyone explain why cd fails when the output is redirected to a pipe?

E.g.:

james@machine:~$ cd /tmp                          # fine, no problem
james@machine:~$ cd /tmp | grep 'foo'             # doesn't work
james@machine:~$ cd /tmp | tee -a output.log      # doesn't work
james@machine:~$ cd /tmp >out.log                 # does work

Verified on OSX, Ubuntu and RHEL.

Any ideas?

EDIT: Seem strange that I'm piping the output of cd? The reason is that it's from a function wrapping arbitrary shell commands with log entries and dealing with output.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

囍笑 2024-07-18 20:20:17

当您重定向输出时,它会生成一个子 shell 进程,更改子进程中的目录,然后退出。 当您不重定向输出时,它不会生成任何新进程,因为它是内置 shell 命令。

When you redirect the output, it spawns a child shell process, changes the directory in the child process, and exits. When you don't redirect the output, it doesn't spawn any new process because it is a built-in shell command.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文