watch command examples to run a command repeatedly or monitor dynamically changeable files (like /proc/*)

Watch command is a really neat tool and comes in handy in many situations. The watch command can be used to monitor any file or script periodically. It runs every 2 seconds by default and it will run until interrupted.

# watch -h
Usage: watch [-dhntv] [--differences[=cumulative]] [--help] [--interval=[n]] [--no-title] [--version] [command]
  -d, --differences[=cumulative] highlight changes between updates
  (cumulative means highlighting is cumulative)
  -h, --help    print a summary of the options
  -n, --interval=[seconds]  seconds to wait between updates
  -v, --version    print the version number
  -t, --no-title   turns off showing the header

The basic syntax of watch command is :

# watch [-n seconds] [-d] [command]

Here,

-d flag will highlight the differences between successive updates.
-n flag is to specify the interval. The default value is 2 seconds.

Here’s a sample output:

# watch -n 10 -d ls -lt

Every 10.0s: ls -lt                                             Tue Feb 14 12:27:43 2017

total 0
-rw-r--r-- 1 root root 0 Feb 14 12:27 new_file_just_created
-rw-r--r-- 1 root root 0 Feb 14 10:46 file1
-rw-r--r-- 1 root root 0 Feb 14 10:46 file2
-rw-r--r-- 1 root root 0 Feb 14 10:46 file3

Here,

Every 10.0s : is the time interval to run the watch command. i.e. 10 seconds.
ls -lt : is the command to be executed every 10 seconds.
Tue Feb 14 12:27:43 2017 : is the current date and time.

Example 1 : Monitoring a dynamically changing file like /proc/meminfo

There is a way to monitor any file on the system with the command watch.

The command:

# watch -n 10 -d  cat /proc/meminfo

would produce an output of the meminfo status every 10 seconds on the screen and will highlight if any changes.

Example 2 : look for the change in the content of a directory

Another excellent use of the watch command is to keep an eye on the contents of the directory and see if any new file is getting added or removed.

# watch -d ls -lt

-lt switch in the ls command displays the latest modified file at the top.

Example 3 : Removing the title/header from the output.

In case you do not want to print the header in the output of watch command, you can use the –no-title or -t option.

# watch -t -d ls -lt

total 0
-rw-r--r-- 1 root root 0 Feb 14 10:47 new_file_just_created
-rw-r--r-- 1 root root 0 Feb 14 10:46 file1
-rw-r--r-- 1 root root 0 Feb 14 10:46 file2
-rw-r--r-- 1 root root 0 Feb 14 10:46 file3

Example 4 : Highlighting cumulative difference

In case you want to highlight the cumulative difference in the output, you can use the -d=cumulative switch in the command. For example :
The output after adding a new file – new_file1 :

The output after adding another new file – new_file2 :

Related Post