How to use watch command.

How To Use Watch Command.

In this tutorial, we will introduce you to the watch command.

watch is used to run any arbitrary command at regular intervals and displays the output of the command on the terminal window.

The watch utility is a part of the procps (or procps-ng) package which is pre-installed on nearly all Linux distributions.

 

How to Use the watch Command

The syntax for the watch command is as follows:

watch [OPTIONS] COMMAND

To better illustrate how the watch command works let’s run the date command:

watch date

 

How to Change the Time Interval.

he -n (–interval) option followed by the desired number of seconds allows you to change the time interval between updates:

watch -n INTERVAL_IN_SECONDS COMMAND

For example, to monitor your disk space usage with the df command and refresh the screen every five seconds on you would run:

watch -n 5 df -h

 

Highlighting the Difference Between Updates.

The -d (–difference), option will cause watch to highlight the changes between successive updates.

watch -d COMMAND

Let’s say you want to monitor the system uptime by running the uptime command and to highlight the changes. The command would be:

watch -d uptime

If you want the highlights to be sticky, pass =cumulative to the -d option. This means that all values that have ever changed will stay highlighted.

watch -d=cumulative COMMAND

 

Commands with Pipes

If you want to execute a command that contains pipes you need to enclose the command in single or double quotes. If you don’t enclose the full command watch will run just the first command and then pipe its output to the next command in the pipeline.

watch 'COMMAND_1 | COMMAND_2'

For example, the following command will monitor the number of active connections on port 80 using a combination of the netstat and grep utilities:

watch "netstat -anp | grep -c ':80\b.*LISTEN'"

 

Conclusion

By now you should have a good understanding of how to use the Linux watch command. You can always view all available watch command options by typing man watch in your terminal.