Leaderboard ad

7.17.2015

Run Command At Regular Intervals Infinitely - Watch Command

Sometimes it is necessary (or just desired) to run a command repeatedly every n seconds.  When I first started using Linux some years back I saw someone use a while loop that was always true, coupled with a sleep and clear commands to make a command run infinitely every n seconds.

Here is an example:

while true; do dig +short putorius.net; sleep 4; clear; done

It wasn't until some time later I found the little known "watch" command.

Watch is used when you need to run a command infinitely to monitor the output.  The console is cleared which makes it easy to observe changes to the output. Watch will run indefinitely or until it is stopped using the CTRL+C combination.

Let's take a look at the basic functions of watch and some of it's options.

To get the same results as the while loop above, we can simply do:

watch -n 4 dig +short putorius.net

NOTE: By default watch will run every two seconds, if this is desired the "-n" switch can be left out.

Sample output



In the screenshot above you can see there is a header that shows you the interval and the command which is being run on the left side and the current time and date on the right side.  That is followed by the output of the command.

There are a few very useful options that are incorporated with watch.

Differences option (-d):

Using -d will tell watch to highlight all the changes on each iteration of the command.  The screenshot below is an example if a difference being highlighted.

NOTE: The highlighting may look different depending on your terminal/console color settings.


The highlighted differences will disappear during the next iteration of the command.  To keep all the differences highlighted use the -d=cumulative option.  For example:

watch -d=cumulative dig +short putorius.net

Exit on error (-e):

Using -e will tell watch to exit if the given command exits with a non-zero or error status.

No header option (-t):

Using -t option will turn the header information (Number of seconds, command and current date info at top of display) off.

Here is a screenshot of watch running with the -t option:


Exit on output change (-g):

Using -g will tell watch to exit when the output of the command changes.

Watch can also be used on a pipeline of several commands for more in depth monitoring of output.  For example let's say we wanted to monitor the query time of the DNS server, we can pipe several commands together like so:

watch 'dig putorius.net | grep Query'

NOTE: If using a pipeline it must be enclosed in quotes, either single or double

For more options you can enter "watch -h" on the command line, or check the man page.




No comments:

Post a Comment