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:

while ((1)) ; do
    if [[ "$old" == "$current" ]] ; then
      echo "command gave same output"
      echo "number of identical, consecutive runs: $n"
      if [[ $n -eq $breaklimit ]] ; then
      echo "command gave different output"
      sleep 2
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


This seems to work (on Linux):

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


  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.


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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.