Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top