本文介绍了可以使用相同的输入文件作为管道命令的输出吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下内容:

cat file | command > file

这是好习惯吗?难道这会在我们读取输入文件的同时覆盖输入文件,还是总是先在内存中读取它,然后通过管道传递给第二个命令?

Is this good practice? Could this overwrite the input file as the same time as we are reading it, or is it always read first in memory then piped to second command?

很明显,我可以将临时文件用作中间步骤,但我只是想知道..

Obviously, I can use temp files as intermediary step, but I'm just wondering..

t=$(mktemp)
cat file | command > ${t} && mv ${t} file

推荐答案

否,这不行.管道中的所有命令同时执行,并且外壳程序在执行命令之前准备重定向.因此,该命令很可能在cat读取文件之前将其覆盖.

No, it is not ok. All commands in a pipeline execute at the same time, and the shell prepares redirections before executing the commands. So, it is likely that the command will overwrite the file before cat reads it.

您需要moreutils中的 sponge(1).

You need sponge(1) from moreutils.

这篇关于可以使用相同的输入文件作为管道命令的输出吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:21