Shell数据管道并行执行疑问:两类管道输出为何不同?
Great question! Let's break down exactly what's happening here, because shell pipes are about more than just parallel execution—they also tie together the input/output streams of the commands involved, which is the key to understanding the difference.
First, a Quick Refresher on Shell Pipes
When you run cmd1 | cmd2, the shell does two core things:
- Launches both commands at the same time (parallel execution, as you noted).
- Connects
cmd1's standard output (stdout) directly tocmd2's standard input (stdin).
The behavior of your two examples hinges on which command sits on which side of the pipe, and whether those commands actually use their connected streams.
Example 1: sleep 3 | echo "Hello world."
Let's walk through this step by step:
- The shell starts
sleep 3andecho "Hello world."at the same moment. echois built to print the arguments you pass it—it doesn't care about its stdin (which is connected tosleep 3's stdout). Instead,echosends its output straight to your terminal (its default stdout destination).- So
echoimmediately prints "Hello world." to the screen and exits. Meanwhile,sleep 3runs in the background for 3 seconds before finishing. That's why you see the message first, then wait 3 seconds for the shell prompt to return.
Example 2: echo "Hello World" | sleep 2
This is where the pipe's stream connection changes everything:
- Again, both commands launch simultaneously.
- Now,
echo's stdout is linked tosleep 2's stdin. Whenechoruns, it writes "Hello World" to this pipe instead of your terminal. - But
sleephas zero interest in reading from stdin—it just waits for the specified 2 seconds. The pipe holds the "Hello World" data, but no one ever reads it. - When
echofinishes writing, it exits.sleepcontinues to run for its full duration, then exits. At that point, the pipe is destroyed, and the unread "Hello World" data is discarded forever. That's why you never see the message.
Why Parallel Execution Doesn't Fix This
Parallel execution just means both commands start at the same time—it doesn't change where their input/output is directed. The critical difference is which command is sending output to the terminal vs. sending it to a pipe that's never read.
A Quick Fix to See the Output in Example 2
If you want to force the message to show up even when piping to sleep, you can redirect echo's output directly to the terminal (bypassing the pipe):
echo "Hello World" > /dev/tty | sleep 2
Or use tee to send the output to both the terminal and the pipe:
echo "Hello World" | tee /dev/tty | sleep 2
内容的提问来源于stack exchange,提问作者Shreya Batra

