How to Run a Command Periodically in Linux using Watch

The requirement of periodically running a command or a process in Linux is quite common. From clean up scripts, to duplicate file removal commands, to automated periodic upgrades, everything can be configured to run periodically in Linux.

Usually, the way to achieve this is to configure Cron jobs, which are handy when it comes to automation scripts and background jobs. However, if you need to run a command or program periodically and view its output interactively, i.e., in (almost) real-time; Cron cannot be used, as it saves all the output to log files.

Today we will learn the watch command which enables us to run a command or program periodically and display real-time output.

The basic syntax for using the watch command is:

$ watch command_name

This will run the command ‘command_name’ every 2 seconds, which is the default time period.

$ watch ps -ef
List Running Linux Processes
List Running Linux Processes

The above command will call ‘ps -ef’ (used to display running processes and their resource usage) every 2 seconds, so we can see the updated resource usage regularly.

Run a Linux Command Every One Minute

To specify the time interval for a periodic run, use the -n option.

$ watch -n time_interval_in_seconds command

For example, to run a Linux command or program every 1-minute use the following command.

$ watch -n 60 ps -ef 

This will obviously run the ‘ps -ef’ command every 1 minute.

Run Linux Command Every Minute
Run Linux Command Every Minute

Another interesting option is the argument -d, which will highlight the difference in the output after every periodic run of the command. For example, let’s run the ps command again, this time sort the output in descending order of memory usage, so we can see the highlighted difference easily.

$ watch -d -n 5 ps aux --sort -%mem
Find Top Running Processess By Memory Usage
Find Top Running Processes By Memory Usage

As seen above, it highlighted the values which changed in the current run of the ps command. Note that this will only highlight the difference between the two immediate runs, and not across all runs.

Conclusion

We saw how the simple use of the watch command enabled us to run programs in Linux periodically. The command watch has more options available to really help the user customize his or her periodic runs. Make sure you check them out on the man page.

$ man watch

Thanks for reading and let us know which programs you used or will use with Watch to view real-time output!

Got something to say? Join the discussion.