2023-04-03

Watch Command in Linux

Watch Command in Linux

The watch command in Linux is an indispensable tool for anyone who needs to monitor changes to files, directories, or even to keep an eye on system performance in real time. Essentially, the watch command enables you to execute a command or script periodically, displaying the output on the screen. This is invaluable when you want to actively observe the output of a command without manually running it over and over again.

Syntax and Options

The basic structure for the watch command is as follows:

bash
$ watch [options] command

Here, command represents the command you want to execute periodically, and [options] represents the various optional parameters you can use to modify how watch functions. Below are some of the common options that can be used with the watch command:

  • -n, --interval
    This option allows you to specify the interval between command executions in seconds. The default is 2 seconds.
  • -d, --differences
    This highlights the differences between successive command outputs. It is very helpful in observing what exactly has changed.
  • -t, --no-title
    This option turns off the header which normally displays the command, current time, and the interval.
  • -h, --help
    Displays a help message explaining the usage of the watch command.

Practical Examples

Monitoring Free System Memory

As a system administrator, keeping an eye on system memory can be crucial. You can use the watch command to monitor the memory usage. For example:

bash
$ watch free -m

This command uses free to display the amount of free system memory in megabytes and updates the output every 2 seconds (default).

Observing Changes in a Directory

Suppose you're waiting for a file to be added to a directory. Instead of running ls repeatedly, you can use:

bash
$ watch -n 1 ls /path/to/directory

This command will list the contents of the directory every second, allowing you to see when the file has been added.

Monitoring Network Interface Statistics

To keep an eye on network traffic, you can use the watch command along with the ifconfig command like this:

bash
$ watch -n 2 ifconfig eth0

This will display the network interface statistics for eth0 and will update every 2 seconds.

Observing CPU Load

By combining watch with the uptime command, you can monitor the CPU load of your system:

bash
$ watch uptime

This will display the system's uptime and load averages, updating every 2 seconds.

Installing Watch command on MacOS

The watch command doesn't come pre-installed on MacOS. However, you can easily install the watch command via HomeBrew. In the Terminal, type the following command and press Enter:

bash
$ brew install watch

This will download and install the watch command.

Ryusei Kakujo

researchgatelinkedingithub

Focusing on data science for mobility

Bench Press 100kg!