[commandline stuff] -> a more intelligent 'watch' command

I sometimes use the 'watch' command to monitor for instance a large filecopy job or download or whatever.

watch is a nice tool to do such things. It runs a command of your choice every few seconds and clears the terminalscreen in between and you can modify the value of those every-few-seconds (default 2 seconds) to whatever you like.

Now, I hate to run commands unnecessary ... might be OCD or whatever ... I just don't like wasting CPU time. :wink:
With watch you have the to adjust the delay between screenupdates manually so you have to guess what interval is optimal.

That gave me an idea:
Why not setting the delay between commands automatically ?
Start with a 2 second delay between commands and if a screenoutput does not change just increase the delay until it does.

This is the result and it works like a charm. It works exactly the same as the regular watch command but it sets the interval automatically and lacks any options.

#!/bin/bash
# Initial delay value in seconds to wait between command runs
delay=2

# Maximum delay value in seconds to wait between command runs
max_delay=3600

while :
do
	# Your command is executed here
	output=$( eval "$*" )

	# decide how long to wait until running command again
	if [ "$output" = "$previous_output" ]
	then
		(( delay < max_delay )) && (( ++delay ))
	else
		clear ; echo "$output"
		previous_output="$output"
	fi

	echo -ne "\rdelay between updates = $delay sec"
	sleep "$delay"
done
3 Likes