watch – Periodically execute a command with output

The watch command is a Linux utility that periodically executes a command and displays its output on the terminal. This command is useful when you want to monitor the output of a command that changes over time. The watch command can be used to monitor system resources, log files, and other commands that produce dynamic output.

Overview

The basic syntax for the watch command is as follows:

watch [options] command

Here, command is the command that you want to execute periodically, and options are optional arguments that you can provide to modify the behavior of the watch command.

For example, if you want to monitor the output of the free command every 5 seconds, you can use the following command:

watch -n 5 free

In this example, the -n option specifies the interval at which the free command should be executed. The output of the free command will be displayed on the terminal every 5 seconds.

Another example is to monitor the contents of a log file in real-time. To achieve this, you can use the following command:

watch tail /var/log/syslog

This command will display the last 10 lines of the /var/log/syslog file and update the output every 2 seconds.

Options

The following table lists the available options for the watch command:

Option Description
-n or --interval Specifies the interval at which the command should be executed. The default value is 2 seconds.
-d or --differences Highlights the differences between the current and previous output of the command.
-t or --no-title Removes the title from the top of the output.
-h or --help Displays the help message and exits.
-v or --version Displays the version information and exits.

Troubleshooting Tips

  • If the output of the command is too long, it may be difficult to read on the terminal. You can use the less command to scroll through the output:
watch command | less
  • If the command that you want to execute requires elevated privileges, you may need to run the watch command with sudo:
sudo watch command
  • If you encounter any errors while using the watch command, make sure that the command that you are trying to execute is valid and that you have the necessary permissions to execute it.

Notes

  • The watch command is not installed by default on some Linux distributions. You may need to install it using your package manager. For example, on Ubuntu and Debian, you can install it using the following command:
sudo apt-get install watch