Reputation: 509
For example, consider invoking this shell command in an empty directory:
ls | cat | cat | cat > file; cat file
When I actually tested, the result was always:
file
But is this behaviour guaranteed by POSIX? I read section 2.7 redirection and 2.9.2 pipeline from the opengroup POSIX standard page, but I couldn't find anything mentioned about this.
And there was one statement that seems relevant, but I couldn't really understand what it means since I'm not native English user. The statement was this:
The standard input, standard output, or both of a command shall be
considered to be assigned by the pipeline before any redirection
specified by redirection operators that are part of the command (see
Redirection).
Upvotes: 2
Views: 169
Reputation: 50795
No, it's not.
Pipeline components are expanded, redirected, and executed in parallel. In your example, ls
may outrun cat > file
and retrieve the list of files before file
is created, and vice versa. You can't rely on cat > file
winning the race every time.
In order to ensure that the redirection is performed before any component of the pipeline is executed, you need to enclose the pipeline in braces, and move the redirection outside:
{ ls | cat | cat | cat; } > file
cat file
Upvotes: 3