How to Use the watch Command to Execute a Program Periodically in Linux

Sometimes in Linux, you need to monitor the output of a command continuously. For example, you might want to watch the memory usage change over time using the free command, or monitor the status of a downloading file using ls -l. Instead of manually typing and executing the command over and over again, you can use the watch command to run it automatically on a loop.

How to Use the Watch Command

The watch command executes a specified program periodically, clearing the terminal screen and showing the updated output each time.

To use it, simply type watch followed by the command you want to monitor. For example, to monitor your system’s memory usage, open your Terminal and type:

watch free -m

Press Enter. Your terminal will clear, and the output of the free -m command will appear. By default, the watch command executes the program every 2.0 seconds. A header at the top of the terminal will display the interval, the command being run, and the current date and time.

To exit the watch screen and return to your normal terminal prompt, press Ctrl + C.

How to Change the Refresh Interval

If you want the command to execute faster or slower than the default 2-second interval, you can use the -n (interval) flag followed by the number of seconds.

For example, to execute the date command every 5 seconds, type:

watch -n 5 date

How to Highlight Differences in Output

One of the most useful features of the watch command is its ability to highlight exactly what changed in the output between the previous run and the current run. You can enable this by using the -d (differences) flag.

For example, to watch the contents of a directory and highlight any changes (like a file size increasing), type:

watch -d ls -l

Any text that changes on the screen will be highlighted, making it incredibly easy to track progressing background tasks.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.