2017-04-14 35 views
1

我试图组成一个命令,将被弯曲,使其每隔几分钟的监控服务器脚本的稳定性(脚本实际路径替换):egrep的输出不转发所有的行到文件

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时间的细节去默认输出:

$ 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的结果。

预先感谢您!

+0

'时间'[适用于整个管道](https://www.gnu.org/software/bash/manual/bashref.html#Pipelines),而不仅仅是第一条命令。 – melpomene

回答

1

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

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

+0

谢谢你指出吉姆。真的很感激它。 我试图做一些关于将stderr和stdout转发到文件的研究,但是下面的选项(在此处推荐)仍然会给出与我原始命令相同的结果: '&> monitor.txt'和 '2>&1 | tee -a monitor.txt' 所以我恐怕我已经回到了我开始的地步。 –

+0

@尼克,你是对的...我已经用一些额外的细节更新了我的答案。 –

+0

非常感谢Jim!我刚刚从我身边得到类似的帖子=) http://stackoverflow.com/questions/13356628/is-there-a-way-to-redirect-time-output-to-file-in-linux 所以下面的语法就像一个魅力: $ while:;做日期+“%T”>> monitor.txt; {time curl - 是http://googel.com | egrep“HTTP | m。\”。 ; } 1 >> monitor.txt 2 >> monitor.txt; echo ================ >> monitor.txt;睡觉30; DONE –