Question: Sometimes I want to repeat a command (or shell-script) frequently (every few seconds). Is there a better way to execute a unix command every n seconds (instead of keep typing the same command manually)?
Answer: Using watch command you can execute a command and view it’s output every few seconds. This is very helpful while monitoring memory usage, disk usage etc.,
You can execute any Unix command using watch command. Watch command will be executed until you terminate it either by CTRL+C or kill the process.
Example 1: Watching for a file creation using watch ls
When you are expecting a file to be created by a background process, or when you are expecting a log file to keep growing in size, you might end-up doing ls command multiple times. Instead, you can use watch command, which will execute the ls command every 2 seconds as shown below.
$ watch ls Every 2.0s: ls Thu Apr 15 16:11:58 2010 flash-plugin-10.0.45.2-release.i386.rpm install_flash_player_10_linux.deb
The first line of the watch command output contains the following header information:
- Every 2.0s : Time interval. i.e ls will be executed every 2 seconds.
- ls : Unix command that is getting executed every 2 seconds.
- Thu Apr 15 16:11:58 2010 : the current date & time.
The rest of the lines are the output of the command that watch is executing. In this example, it displays the output of ls command.
Example 2: Display used & free memory details (with differences highlighted)
The -d option highlights the difference between successive updates.
$ watch -d free -om Every 2.0s: free -om Thu Apr 15 16:11:59 2010 total used free shared buffers cached Mem: 992 87
40 135 37
9Swap: 4095 8 4087
If the memory output doesn’t change on your system, try the -d option with date command to see how it works.
$ watch -d date
Note: Did you know that you can highlight the changes in the top command output?
Example 3: Display available disk space (repeat every 10 seconds)
By default watch command uses 2 second interval, you can change it using -n option. The following example executes df -h command every 10 seconds.
$ watch -n 10 df -h Every 10.0s: df -h Thu Apr 15 16:12:26 2010 Filesystem Size Used Avail Use% Mounted on /dev/sda7 30G 8.6G 20G 31% / tmpfs 497M 964K 496M 1% /dev/shm /dev/sda6 194M 22M 163M 12% /boot
Example 4: Suppress watch header in the output
You can supress the 1st line of the watch command output using option -t as shown below.
$ watch -t ls flash-plugin-10.0.45.2-release.i386.rpm install_flash_player_10_linux.deb