6

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
  • 289,791
  • 117
  • 680
  • 835
Adam Matan
  • 12,289
  • 24
  • 71
  • 90

2 Answers2

6

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
  • 362
  • 2
  • 6
  • 13
Oli
  • 289,791
  • 117
  • 680
  • 835
  • uberwatch's syntax does not parse. `syntax error near unexpected token done` – Artem Russakovskii Mar 01 '18 at 17:31
  • @ArtemRussakovskii Thanks, there were a few errors. Have fixed. – Oli Mar 02 '18 at 14:53
  • Is there a modification to uberwatch that supports multiple commands? For example `uberwatch 2 "date; ls" bash: date; ls: command not found` – Artem Russakovskii Mar 03 '18 at 18:54
  • 1
    On the other hand, `while true; do date; ls; sleep 2; done` works. – Artem Russakovskii Mar 03 '18 at 18:55
  • 1
    @ArtemRussakovskii Since `${@:2}` is encapsulated with double quotes, your command is run like so: `while true; do "date; ls"; sleep 2; done` which gives the same error you get. If you want to run more than 1 command, I'd recommend putting those inside a separate script, and call that script with the `uberwatch` function. Such as: `uberwatch 2 /path/to/the/custom/script` – Dan Mar 05 '18 at 15:37
0

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
  • 1
  • 1
  • 1
    Could you add a bit more detail please? What does this do that the other answer doesn’t? Thank you. – Will Nov 02 '21 at 20:29
  • Sorry, i should have mentioned that i was look for same function but also save the output to a file so i can walk away and analyze the data when i got back. Hence added redirects to store output for each iteration – Jay Nov 02 '21 at 20:42
  • 1
    can you edit your answer to say that? Might help other people - thanks! – Will Nov 02 '21 at 20:43