1. Overview

When we work on the Linux command line, sometimes we want to execute a command periodically and check the output of each execution. The watch command can help us with that.

In this tutorial, we’ll learn this command together through some examples.

2. Introduction to the watch Command

The watch command is a utility from the procps-ng package. This package is by default available on all Linux distros.

We can use the watch command to execute a command at regular intervals. It displays its output on a console or terminal in fullscreen mode.

In this way, we can observe the changes in the command output over time.

The basic usage syntax of the watch command is pretty straightforward:

watch [options] COMMAND

The default interval to execute the given command is two seconds. For example, we can monitor the output of the date command every two seconds:

$ watch date

We will see the output:

To exit the watch command, we press Ctrl-C.

3.  Customize the Update Interval

If we pass the -n (seconds) option to the watch command, we can specify the update interval.

Let’s monitor the output of the date command every three seconds instead of the default two seconds:

$ watch -n 3 date

The output looks like:

At the very beginning of the screen, it lists the interval and the command to watch: Every 3.0s: date in the header.

4. Turn Off the Header in Output

We’ve seen the header in the output of the watch command, showing the interval, command, hostname, and the current system time.

We can use the -t  option to hide the header in the output:

$ watch -t date

Now, we have the output without the header:

5. Highlight the Differences Between Updates

The output of the command we want to watch might not be as simple as the previous example. In this case, it is not so easy for us to see the changes between updates.

The -d option will highlight the differences between successive updates. 

For example, let’s monitor memory usage every two seconds and highlight the changes:

$ watch -d free

The output would be:

6. watch Commands With Pipes

Sometimes we want to execute pipe-chained commands with the watch utility. We must wrap the whole command by quotes:

$ watch "COMMAND1 | COMMAND2 |..."

Now let’s monitor the vim process information by executing the ps command with grep:

$ watch "ps -ef | grep [v]im"

7. Conclusion

In this article, we’ve discussed the usage of the watch command through examples.

Although it’s a simple program, if we use it properly, it can be quite useful.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments