仅当重定向到管道或文件时,awk才会输出 [英] No output from awk only when redirected to pipe or file
问题描述
我有一个相当简单的脚本(在向每行添加时间戳后,从tty打印内容).它可以在命令行上很好地输出,但是用>
重定向输出不起作用.为什么不呢?
I have a rather simple script (print content from a tty after adding timestamp to every row). It outputs nicely on the command line, but redirecting the output with >
does not work. Why not?
这是脚本:
#!/bin/bash
awk '{ print strftime("%Y-%m-%d %H:%M:%S |"), $0; }' "$1"
按原样运行它,就像timecat /dev/ttyACM0
正常工作一样,我在终端中看到了内容.
Running it as is, like timecat /dev/ttyACM0
works fine, I see the content in my terminal.
但是,如果我运行timecat /dev/ttyACM0 > ~/tmp.log
,则什么也不会出现.与tee
相同.该文件在那里,但为空.
But if I run timecat /dev/ttyACM0 > ~/tmp.log
, nothing comes out. Same with tee
. The file is there, but it is empty.
脚本中的awk
是否有些怪异,如何修改它以使重定向有效?
Is there something weird with awk
in the script, how can I modify this to make the redirection work?
推荐答案
所需要做的就是刷新命令中的打印内容,并用以下命令替换最后一个脚本行:
All this needed was to flush the print within the command, replacing the last script row with this:
awk '{ print strftime("%Y-%m-%d %H:%M:%S |"), $0; fflush(); }' $tty
^^^^^^^^^
这篇关于仅当重定向到管道或文件时,awk才会输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!