1

I was trying to compose a command that would monitor the stability of the script on server by curling it every couple of minutes (actual path to script was replaced):

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

The problem is that for some reason part of output is not forwarded to file monitor.txt. So file contains following lines:

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

..while time details go to default output:

$ 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

Could you please point out, what am I missing here? Basically I would run this command in a background and check monitor.txt for results.

Thank you in advance!

Jim Lewis
  • 43,505
  • 7
  • 82
  • 96
Nick Dagaz
  • 75
  • 1
  • 6
  • `time` [applies to the whole pipeline](https://www.gnu.org/software/bash/manual/bashref.html#Pipelines), not just the first command. – melpomene Apr 14 '17 at 16:45

1 Answers1

1

The time command sends its output to stderr, not stdout. Your redirection only affects stdout, so the time output ends up going to the console.

To add to the confusion, bash also has a builtin time command, which is a bit trickier to redirect. If you use /usr/bin/time instead of time, you should be able to redirect its output with the 2>&1 syntax. Or if you prefer the bash builtin version of the command, you can see this answer for a way to redirect its output.

Community
  • 1
  • 1
Jim Lewis
  • 43,505
  • 7
  • 82
  • 96
  • Thank you for pointing this out Jim. Really appreciated it. I have tried to do some research about forwarding both stderr and stdout to file, however following options (recommended here on SO) still give same result as my original command: ` &> monitor.txt` and ` 2>&1 | tee -a monitor.txt` So I am afraid that I am back to the point I begun from. – Nick Dagaz Apr 14 '17 at 17:01
  • @Nick, you're right...I've updated my answer with a few additional details. – Jim Lewis Apr 14 '17 at 17:17
  • Thank you very much Jim! I have just got to similar post from my side =) http://stackoverflow.com/questions/13356628/is-there-a-way-to-redirect-time-output-to-file-in-linux So following syntax works like a charm: $ while :; do date +"%T" >> monitor.txt; { time curl -Is http://googel.com | egrep "HTTP|m.\." ; } 1>>monitor.txt 2>> monitor.txt; echo ================ >> monitor.txt; sleep 30; done – Nick Dagaz Apr 14 '17 at 17:22