击:它是确定使用相同的输入文件作为一个管道命令的输出? [英] Bash: Is it ok to use same input file as output of a piped command?

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

问题描述

考虑是这样的:

 猫文件|命令>文件

这是很好的做法?难道这覆盖输入文件的同时,我们读它,或者它总是先在内存中读出,然后输送到第二个命令?

显然,我可以使用临时文件作为中间步骤,但我只是想知道..

  T = $(mktemp的)
猫文件|命令> $ {T】&放大器;&安培; MV $ {T】文件


解决方案

没有,那也不行。在管道中的所有命令执行的同时,并在执行命令之前壳prepares重定向。所以,它很可能是该命令将覆盖该文件猫读取之前

您需要海绵(1)从moreutils。

Consider something like:

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

解决方案

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.

You need sponge(1) from moreutils.

这篇关于击:它是确定使用相同的输入文件作为一个管道命令的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆