pipe - 是否保证 POSIX shell 在执行管道中的任何命令之前始终打开文件进行重定向?

标签 pipe sh posix pipeline io-redirection

例如,考虑在空目录中调用此 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/

相关文章:

python - 从外部操纵 Firefox 的 View

c - 多线程素数生成器

客户端服务器循环导致管道损坏 - C

c++ - Windows api中是否有非命名管道?

shell - 应该如何处理由变量扩展产生的反斜杠?

c - 有没有一种编程方法可以判断符号链接(symbolic link)是否指向 C 中的文件或目录?

linux - 从内部检测 chroot jail

java - 在linux中使用java web服务进行IPC(进程间通信)

c++ - linux 终端中的进度条

linux - 在 shell 中写入输出流