11

gnu watch is a very useful tool for inspecting a program output: It executes the program and shows the output full-screen every 2 seconds.

Sometimes, I don't want the previous output to be erased, but rather be printed line by line with a time stamp. For that, I use bash scripts like:

while true; 
    do echo -n "`date`   "; 
    ssh ubuntu@server -o ConnectTimeout=1 "uptime" ; 
    sleep 1; 
done

Is there a watch-like tool that can run a command and display its output with a timestamp in a line without erasing previous output?

Oli
  • 299,380
Adam Matan
  • 12,919

3 Answers3

9

I'd say you've found it in simple loops but you could do a number of things from here:

Write a function to handle that for you

function uberwatch {
    # call: uberwatch <interval> <command>
    while true; do
        "${@:2}";
        sleep $1;
    done
}

You could lodge that somewhere around your ~/.bashrc.

Log the output to file but keep viewing with watch

watch "command | tee -a watchlog.log"

You'd still only see the latest run-through but you could dig through a historical log if you needed to.

Abdull
  • 734
Oli
  • 299,380
1

while true; do date >> /vat/tmp/watch.log; sleep 600; ls -l filename >> /var/tmp/watch.log; done

I like the while loop mentioned by Artem above but was looking to store the data in a file so i can analyze it when i got back, hence added redirects to a file. In my case watching file every 10mins and ls -l for file size

-Jay

Jay
  • 11
-1

I like Oli's modified watch solution, but I like the idea of viewing the log in real time instead of digging through it later.

Here's an idea:

watch 'echo $(date && command 2>&1 | tail -n 1) >> watchlog.log && cat watchlog.log | tail'

Explanation:

  • echo avoids a newline between date and command.
  • >> appends to the file, same as | tee -a but without also duplicating in watch output.
  • 2>&1 combines stderr with stdout to make sure you see everything, including errors.
  • | tail -n 1 restricts output to the final line (the one containing the date output) for cleaner real-time viewing. This may or may not be your desire for the log file contents.
nogjam
  • 99
  • 3