2

Is there a possibility to watch a command until the output remains the same?

With watch -g, one can check if a commands results changed and use this as a trigger to go to the next step in a script. But what if I want to check for the moment a command returns the same output for two consecutive (or a defined number of consecutive) runs?

Something like

 watch --exit-on-constant-output --number-of-minimum-identical-runs=10 <command>

Currently the only way that comes into my mind would be a script that saves the output in the first run and then compares like:

#!/bin/bash
breaklimit=4
n=0
old=$(command)
while ((1)) ; do
    current=$(command)
    if [[ "$old" == "$current" ]] ; then
      echo "command gave same output"
      n=$((n+1))
      echo "number of identical, consecutive runs: $n"
      if [[ $n -eq $breaklimit ]] ; then
        break
      fi
    else
      echo "command gave different output"
      old="$current"
      n=0
      sleep 2
    fi
done
echo "run next command"

Works fine for e.g. using $(($RANDOM/10000)) as command. But maybe there is a more elegant way?

PS: Maybe some made-up use case will help. Let's say I connected a thermometer to my processing machine and want to start production once the temperature has leveled. So I will query the thermometer every 60 seconds for the current temperature.

1 Answer 1

2

This seems to work (on Linux):

while :
do
    timeout 8 watch -g my-command my-args || break
done

NOTES:

  1. instead of "number of runs" as you said, this merely specifies the number of seconds the output must be the same

  2. if the my-command is one that does not like being killed while running this may not be suitable, or at least the timeout value and watch's -n option need to be tweaked to reduce the chances of that happening.

EXPLANATION:

The basic idea is that the timeout command exits with error (exit code 124) if the command is still running at the end of the timeout. (You can run

timeout 2 date; echo $?
timeout 2 sleep 3; echo $?

to see this in action.

We combine that with the watch -g. If watch exits before the timeout (i.e., there has been a change in the output), timeout returns with exit code 0, and the loop continues.

If the output has not changed for (in my example) 8 seconds, watch will be killed by the timeout, and timeout will exit with an error, and break the loop.

1
  • Time-based is a nice idea!
    – FelixJN
    Commented Jan 14, 2021 at 8:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .