James Brady
James Brady

Reputation: 27482

cd doesn't work when redirecting output?

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.

Upvotes: 4

Views: 1079

Answers (1)

Tmdean
Tmdean

Reputation: 9309

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.

Upvotes: 14

Related Questions