Understanding the Linux Command Watch

See changes on your system in real time.

The Linux command watch runs command repeatedly, displaying its output (the first screenful). This allows you to watch the program output change over time. By default, the program is run every 2 seconds; use -n or --interval to specify a different interval.

The -d or --differences flag will highlight the differences between successive updates. The --cumulative option makes highlighting "sticky", presenting a running display of all positions that have ever changed.

Watch will run until interrupted.  

Using Watch

Watch is most useful when you're looking for changes or new output. You would typically use it to find new entries to your log files when debugging. To simulate that, you can run a simple loop that outputs to a "log" file.

First, create the loop in a script. Something like this will work.

#! /bin/bash

while [ $x -gt 0 ]; do
x-$[ $x-1 ]
echo $x >> test.log
sleep 2

Then, create an empty log.

touch test.log

Set up watch to monitor the contents of the log file.

watch -d cat test.log

Finally, run your script from a different terminal window.

chmod +x script.sh

Turn your attention back to the terminal running the watch command to see each line of output appear.

Obviously, you wouldn't do this exact sort of thing, but imagine running something like:

watch -d tail /var/log/apache2/error.log

That makes a lot more sense, and it could be a huge time saver when trying to debug a web server issue.

Command is given to sh -c which means that you may need to use extra quoting to get the desired effect.

POSIX option processing is used (i.e., option processing stops at the first non-option argument). This means that flags after command don't get interpreted by watch itself.

More Examples of The Linux Watch Command

To watch for mail, you might do:

watch -d ls /var/spool/mail

To watch the contents of a directory change, you could use:

watch -d ls /~/Downloads

If you're only interested in files owned by user joe, you might use:

watch -d find / -user joe

Use the man command (% man) to see how a command is used on your particular computer.

Was this page helpful?