在shell中执行管道组件的顺序 [英] The order in which pipeline components are executed in shell
问题描述
ls | wc
此处按 ls
和 wc
的顺序执行?还是 |
和 wc
只是 ls
的参数?
In which order ls
and wc
executed here? Or, are |
and wc
just arguments to ls
?
推荐答案
在表达式中 ls |wc
,您的外壳程序将大致执行以下操作:
In the expression ls | wc
, your shell will perform roughly the following actions:
- 启动两个子外壳A和B,并将A的标准输出连接到B的标准输入.
- 在子外壳A中,启动命令
ls
- 在子外壳B中,启动命令
wc
- 等到所有子shell终止
- 将
$?
设置为子外壳B的退出状态(即wc
的退出状态)
- 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
)
bash 手册页上有更多详细信息:
The bash
manpage has more details:
管道
管线是由一个或多个命令分隔的序列,其中一个或多个控制运算符
|
或|&
.管道的格式为:
[time [-p]] [ ! ] command [ [|│|&] command2 ... ]
command 的标准输出通过管道连接到 command2 的标准输入.在进行任何重定向之前执行此连接由命令指定(请参见下面的 REDIRECTION
).如果使用 |&
,则命令的标准错误连接到 command2 的标准输入通过管道;它是 2>&1 |
的简写.这隐含重定向后执行标准错误的重定向由命令指定.
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 REDIRECTION
below). If |&
is used, the
standard error of command is connected to command2's standard input
through the pipe; it is shorthand for 2>&1 |
. This implicit
redirection of the standard error is performed after any redirections
specified by the command.
管道的返回状态是最后一条的退出状态命令,除非启用了 pipefail
选项.如果 pipefail
是启用后,管道的返回状态是最后一个的值(最右边)命令以非零状态退出,如果全部退出则为零命令成功退出.如果保留字!
在a之前管道,该管道的退出状态是如上所述的退出状态.Shell等待所有命令在管道中终止,然后再返回值.
The return status of a pipeline is the exit status of the last
command, unless the pipefail
option is enabled. If pipefail
is
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.
如果 time
保留字在管道之前,则经过时间以及当执行管道终止. -p
选项将输出格式更改为由POSIX指定. TIMEFORMAT
变量可以设置为一种格式字符串,指定应如何显示计时信息;请参阅下面的Shell变量下的 TIMEFORMAT
的说明.
If the time
reserved word precedes a pipeline, the elapsed as well as
user and system time consumed by its execution are reported when the
pipeline terminates. The -p
option changes the output format to that
specified by POSIX. The TIMEFORMAT
variable may be set to a format
string that specifies how the timing information should be displayed;
see the description of TIMEFORMAT
under Shell Variables below.
管道中的每个命令都作为单独的进程执行(即,一个子外壳).
Each command in a pipeline is executed as a separate process (i.e., in a subshell).
这篇关于在shell中执行管道组件的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!