例如,考虑在空目录中调用此 shell 命令:
ls | cat | cat | cat > file; cat file
当我实际测试时,结果总是:
file
但是 POSIX 保证这种行为吗?我从 opengroup POSIX 标准页面阅读了第 2.7 节重定向和第 2.9.2 节管道,但我找不到任何关于此的内容。
有一个说法似乎相关,但我无法真正理解它的含义,因为我不是母语为英语的用户。声明是这样的:
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).
最佳答案
不,不是。
管道组件被并行扩展、重定向和执行。在您的示例中,ls
可能会超过 cat > file
并在创建 file
之前检索文件列表,反之亦然。您不能依靠 cat > file
获胜 the race每次。
为了确保在执行管道的任何组件之前执行重定向,需要将管道用大括号括起来,并将重定向移到外面:
{ ls | cat | cat | cat; } > file
cat file
关于pipe - 是否保证 POSIX shell 在执行管道中的任何命令之前始终打开文件进行重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68872057/