Shell – Behavior of stdin/stdout in conjunction with subshells and cd command

cd-commandio-redirectionpipesubshell

I have the following series of commands:

cd / && ls | ( cd /tmp && cat >dumpfile)

This series of commands does the following: it creates a file named /tmp/dumpfile. This file contains a listing of the root directory.

The cd / && ls output gets piped to a subshell. What I find odd is that in the subshell, instead of cd /tmp swallowing the ls output, the later cat >dumpfile gets it and writes it to a file. What is going on here?

Best Answer

The pipe sets up stdout to go from ls to the subshell.

In the subshell, cd /tmp and cat are done in the same process.

cd /tmp doesn't read from stdin (the pipe), so when cat reads from stdin, it gets all of ls's output.