Linux 输出重定向到文件

问题描述 投票:0回答:1

这是在 RHEL 7 中。

简单的shell脚本:

while [ 1 ] ;
do
  echo "Test Message 1"
  echo "Test Message 2"
  echo ""
  sleep 10
done

以下效果很好:

./loop-test.sh | gawk '{ print strftime("[%Y-%m-%d %H:%M:%S]"), $0 }'
[2023-12-21 10:04:47] Test Message 1
[2023-12-21 10:04:47] Test Message 2

我想将输出重定向到文件。所以我做了: ./loop-test.sh | 循环测试gawk '{ print strftime("[%Y-%m-%d %H:%M:%S]"), $0 }' > t.txt

它创建输出文件 t.txt,但它是空的。我尝试了几次重定向......包括“tee”但没有运气。

有没有办法可以捕获文件中的输出?

shell awk io-redirection
1个回答
0
投票

这是由于输出缓冲而发生的。当输出重定向到文件时,

gawk
shell
都会在将输出写入文件之前缓冲输出。要在 gawk 中禁用缓冲,可以使用
fflush()
函数。比如:

./loop-test.sh | gawk '{ print strftime("[%Y-%m-%d %H:%M:%S]"), $0; fflush() }' > t.txt
© www.soinside.com 2019 - 2024. All rights reserved.