加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

linux – shell重定向位置的区别

发布时间:2020-12-13 22:58:41 所属栏目:Linux 来源:网络整理
导读:这两行之间有什么区别吗? for i in $(seq 1 10); do echo $i - `date`; sleep 1; done /tmp/output.txtfor i in $(seq 1 10); do echo $i - `date` /tmp/output.txt ; sleep 1; done 因为Robert told me表示第一个只在for循环外部产生I / O OP. 但是,如果我
这两行之间有什么区别吗?

for i in $(seq 1 10); do echo $i - `date`; sleep 1; done >> /tmp/output.txt

for i in $(seq 1 10); do echo $i - `date` >> /tmp/output.txt ; sleep 1; done

因为Robert told me表示第一个只在for循环外部产生I / O OP.

但是,如果我输入tail -f /tmp/output.txt,这行为方式完全相同.

解决方法

如果他们成功,他们也会这样做.但是,如果因任何原因失败,可能会有明显的差异.

第一个:

for ...; do
   # things
done >> file

这将在循环完成后重定向到文件.但是,只要Bash决定刷新缓冲区,就可能发生这种情况.

想象一下,在迭代次数3之后出现了一些问题:你无法分辨出文件中存储的内容.

第二个:

for ...; do
   # things >> file
done

这将在每次迭代时重定向到文件.

想象一下迭代次数3之后出现问题:您确定前两个循环已正确存储在文件中.

从How to redirect output from an infinite-loop program开始:

If your program is using the standard output functions (e.g. puts,
printf and friends from stdio.h in C,cout << … in C++,print
in many high-level languages),then its output is
07001:
characters accumulate in a memory zone which is called a buffer; when
there’s too much data in the buffer,the contents of the buffer is
printed (it’s “flushed”) and the buffer becomes empty (ready to be
filled again). If your program doesn’t produce much output,it may not
have filled its buffer yet.

另外,从the answer you link开始:

Placing the redirection operator outside the loop doubles the
performance when writing 500000 lines (on my system).

这是有道理的:如果你必须在每个循环上刷新,那么只要它发现方便就让Bash刷新需要更多的时间.每次写一行比划线更容易.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读