问题
ls | wc
In which order ls and wc executed here? Or, are | and wc just arguments to ls?
回答1:
In the expression ls | wc, your shell will perform roughly the following actions:
- start two subshells A and B, with A's standard output connected to B's standar input.
- In subshell A, start the command
ls - In subshell B, start the command
wc - wait until all subshells terminated
- set
$?to the exit status of subshell B (i.e. the exit status ofwc)
The bash manpage has more details:
Pipelines
A pipeline is a sequence of one or more commands separated by one of the control operators
|or|&. The format for a pipeline is:[time [-p]] [ ! ] command [ [|│|&] command2 ... ]The standard output of command is connected via a pipe to the standard input of command2. This connection is performed before any redirections specified by the command (see
REDIRECTIONbelow). If|&is used, the standard error of command is connected to command2's standard input through the pipe; it is shorthand for2>&1 |. This implicit redirection of the standard error is performed after any redirections specified by the command.The return status of a pipeline is the exit status of the last command, unless the
pipefailoption is enabled. Ifpipefailis enabled, the pipeline's return status is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands exit successfully. If the reserved word!precedes a pipeline, the exit status of that pipeline is the logical negation of the exit status as described above. The shell waits for all commands in the pipeline to terminate before returning a value.If the
timereserved word precedes a pipeline, the elapsed as well as user and system time consumed by its execution are reported when the pipeline terminates. The-poption changes the output format to that specified by POSIX. TheTIMEFORMATvariable may be set to a format string that specifies how the timing information should be displayed; see the description ofTIMEFORMATunder Shell Variables below.Each command in a pipeline is executed as a separate process (i.e., in a subshell).
回答2:
No,ls not handle the pipe argument,this done by shell.
The content of stdout of ls command was, taken as input of wc from stdin.
ls [stdout]|* [stdin]* wc -l
the command wc will get that stdout content as input.
Here both commands are executed as different process by shell. which means both have different PID.
For Verify youself this answer,use ps|cat. you can see that different process cat and ps.
PID TTY TIME CMD
11695 pts/1 00:00:00 bash
12207 pts/1 00:00:00 ps
12208 pts/1 00:00:00 cat
来源:https://stackoverflow.com/questions/33462120/the-order-in-which-pipeline-components-are-executed-in-shell