3

I'm using watch -g to monitor the output of a command and exit as soon as it changes. The problem is that all the UI elements of watch (including the output of the command that I'm monitoring) disappear as soon as it exits. I want to know what the output changed to before watch exited. Is this possible?

Ryan
  • 31
  • 1
  • 1
    Try `TERM=linux watch -g …`. I got this by trial and error, so it's voodoo, therefore not an answer. Hopefully someone will give you an *educative* answer. – Kamil Maciorowski Jan 04 '23 at 21:27
  • @KamilMaciorowski, I like your approach. If OP doesn't need to compare last and the second last output this is preaty nice solution I would say. – Damir Jan 04 '23 at 23:03
  • @Kamil - looks like that `TERM` doesn't use the alternate buffer... Anyway, I'm marking this as duplicate, if the OP wants to see the output of `watch` he can switch to the alternate buffer per the answer to the duplicate, i.e. run `printf \\33\[\?47h` – don_crissti Jan 04 '23 at 23:46
  • 1
    Does this answer your question? [How to configure screen-restore in a terminal?](https://unix.stackexchange.com/questions/85398/how-to-configure-screen-restore-in-a-terminal) – don_crissti Jan 04 '23 at 23:47

2 Answers2

0
watch -g "ls | tee -a log_file"

In log_file you will get the output of your command. ls is just example, of course you will use your own command or if more of them you should put them in parentheses like in answer below. Credit to this answer.

For easier recognition of differences between last and second last output you could add empty new line and some markation:

watch -g "(echo; echo 'New output below:'; echo '------------------'; ls) | tee -a log_file"
Damir
  • 491
  • 2
  • 4
0

If you're willing to not use watch, try this and it will show the most recent output when the command failed. Replace somecommand with your command.

logFile='/var/log/somecommand.log'
somecommand &> $logFile &
expectedOutput=$(cat $logFile)
while true; do
  somecommand &> $logFile &
  actualOutput=$(cat $logFile)
  if [[ "$actualOutput" != "$expectedOutput" ]]; then
    echo "Process failed, here is the most recent output..."
    echo "$actualOutput"
    exit 1
  fi
  sleep 2
done