1. Overview

In this tutorial, we’ll learn how to automatically repeat any Linux command every X seconds using the command line.

This is particularly useful for automating tasks that need to be performed continuously. Another use case is checking various system health parameters periodically to make sure everything works as expected.

2. Linux watch Command

With this purpose in mind, we’ll have a closer look at the Linux watch command. Since the watch command is part of the procps package, we’ll find it installed on virtually every Linux system by default. Because of this, there should be no installation necessary.

The watch command executes the supplied command every two seconds by default and shows the output in fullscreen.

In the most basic case, we invoke watch by just passing the command we want to execute as the only argument:

watch date
linux watch 1

We can see a couple of things here: In the top left, we find the current execution frequency. In this case, it is two seconds. In the top right, we find the hostname and the current date. Below that, finally, we find the output of the command we invoked, which happens to also be the current date. This output is updated whenever two seconds have passed.

3. Configuration Options

Obviously, there are several command-line arguments we can use to customize this output to our liking.

To change the execution frequency, we use the -n parameter followed by the number of seconds between executions:

watch -n 60 df -h
linux watch 2

This command will execute df -h every minute, showing us the disk usage on our hard drives.

To limit this rather extensive output to the relevant line, we’ll use a pipe.

Whenever we want to use a pipe in a command passed to watch, we’ll need to enclose the entire command in quotes:

watch -n 60 'df -h | grep /sda'
linux watch 3

Now we only display the disk usage on /dev/sda1, which gets refreshed every minute.
If we are not interested in the information in the first line of the output, we can use the -t option to disable the title bar:

watch -t date
linux watch 4

Finally, we can use the -d option to dynamically highlight the differences between different executions of the command we are interested in.

The free command is a good one to try in order to see this in action:

watch -d free

4. Conclusion

To summarize, we learned how we can use the watch command to repeatedly execute commands and customize its output and behavior to our liking.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.