Automatically re-execute a command by a given time interval in bash


There are several use cases where we need to execute a command every 5 seconds or so. Typical examples are watching dynamic directory content, monitoring how a file grows, monitoring disk/memory/CPU usage. In such cases you have to type over and over one command. Here are two examples how to automate this.
 


Plain old endless loop
 


The first option is just loop over and over while executing the command and sleep for a couple of seconds before iterations. Here's a sample that lists the content of /some/dir every 3 seconds:

while true;
do
    clear
    ls -al /some/dir
    sleep 3
done


The watch program
 


There's a dedicated program which does pretty much the same as above - watch. Just append you command and you're done. It also displays fancy header with the actual command, time interval and last refresh time. This example checks the free space every ten seconds:

watch -n 10 df -h

 

No comments yet

Back to articles list

This page was last modified on 2024-11-12 05:45:52