egrep输出不会将所有行转发到文件

时间:2017-04-14 16:42:52

标签: bash time output

我试图编写一个命令来监视服务器上脚本的稳定性,每隔几分钟就会调整一次脚本(替换脚本的实际路径):

while :; do date +"%T" >> monitor.txt; time curl -Is http://googel.com | egrep "HTTP|m.\." >> monitor.txt; echo ================ >> monitor.txt; sleep 30; done

问题在于,由于某种原因,部分输出不会转发到文件monitor.txt。所以文件包含以下行:

$ cat monitor.txt
19:39:10
HTTP/1.1 301 Moved Permanently
================
19:39:40
HTTP/1.1 301 Moved Permanently
================

..而时间细节转到默认输出:

$ while :; do date +"%T" >> monitor.txt; time curl -Is http://googel.com | egrep "HTTP|m.\." >> monitor.txt; echo ================ >> monitor.txt; sleep 30; done

real    0m0.075s
user    0m0.005s
sys     0m0.003s

real    0m0.106s
user    0m0.004s
sys     0m0.005s

请指出,我在这里错过了什么?基本上我会在后台运行此命令并检查monitor.txt以获得结果。

提前谢谢!

1 个答案:

答案 0 :(得分:1)

time命令将其输出发送到stderr,而不是stdout。您的重定向仅影响stdout,因此time输出结束 到控制台。

为了增加混淆,bash还有一个内置time命令 重定向有点棘手。如果您使用/usr/bin/time而不是 time,您应该能够使用2>&1语法重定向其输出。 或者如果你更喜欢命令的bash内置版本,你可以看到this answer的方式 重定向其输出。