Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 653
James Brady Avatar asked Dec 10 '22 22:12

James Brady


1 Answers

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.

like image 113
Tmdean Avatar answered Dec 28 '22 13:12

Tmdean