How to Run or Repeat a Linux Command Every X Seconds Forever

A system administrator often needs to run a command repeatedly in a certain periods of time. Often such tasks can be easily completed with simple cron commands. In most of the cases  this should work, but the shortest period which you can run cron command is every 1 minute. Believe it or not, in many cases this is too slow.

Run Linux Command Every Second
Run Linux Command Every Second

In this tutorial, you will learn a simple scripting techniques to monitor or keep a eye on a particular command in continuously running state similar to top command (continuously monitor the process and memory utilization) for every 3 seconds by default.

We will not stop to discuss the reasons, why you would need to run commands this often. I believe everyone has different reasons for that in their daily jobs or even at home PCs and laptops.

1. Use watch Command

Watch is a Linux command that allows you to execute a command or program periodically and also shows you output on the screen. This means that you will be able to see the program output in time. By default watch re-runs the command/program every 2 seconds. The interval can be easily changed to meet your requirements.

Monitor Memory Usage

“Watch” is extremely easy to use, to test it, you can fire up a Linux terminal right away and type the following command:

# watch free -m

The above command will check your system free memory and update the results of the free command every two seconds.

Monitor Memory Usage in Linux
Monitor Memory Usage in Linux

As seen per the above output, you have a header, displaying information about (from left to right) update interval, command that is being executed and current time. If you wish to hide this header, you can use the -t option.

The next logical question is – how to change the execution interval. For that purpose, you can use the -n option, that specifies the interval with which the command will be executed. This interval is specified in seconds. So let’s say you want to run your script.sh file every 10 seconds, you can do it like this:

# watch -n 10 script.sh

Note that if you run the command like shown above, you will need to cd to the directory (learn Learn 15 cd Command Examples) where the script is located or otherwise specify the full path to that script.

Other useful options of watch command are:

  1. -b – creates a beep sound if the exit of the command is non-zero.
  2. -c – Interprets ANSI color sequences.
  3. -d – highlights the changes in the command output.

Monitor Logged-In Users, Uptime and Load Average

Let’s say you want to monitor logged-in users, server uptime and load average output in continuously phase every few seconds, then use following command as shown:

# watch uptime
Watch Linux Load Average
Watch Linux Load Average

To exit the command, press CTRL+C.

Here, the 'uptime' command will run and display the updated results every 2 seconds by default.

Monitor Progress of Copy Command

In Linux, while copying files from one location to other using cp command, the progress of data is not shown, to see the progress of data being copied, you can use the watch command along with du -s command to check the disk usage in real time.

# cp ubuntu-15.10-desktop-amd64.iso /home/tecmint/ &
# watch -n 0.1 du -s /home/tecmint/ubuntu-15.10-desktop-amd64.iso 
Monitor Progress of Copy Command
Monitor Progress of Copy Command

If you think that the above process is too complicated to achieve, then I suggest you to go for Advance copy command, which shows progress of data while copying.

2. Use sleep Command

Sleep is often used to debug shell scripts, but it has many other useful purposes as well. For example, when combined with for or while loops, you can get pretty awesome results.

If you are new to bash scripting, you can check our guide about bash loops here.

In case this is the first time you hear about the "sleep" command, it is used to delay something for a specified amount of time. In scripts, you can use it to tell your script to run command 1, wait for 10 seconds and then run command 2.

With the above loops, you can tell bash to run a command, sleep for N amount of seconds and then run the command again.

Below you can see examples of both loops:

for loop Example

# for i in {1..10}; do echo -n "This is a test in loop $i "; date ; sleep 5; done

The above one liner, will run the echo command and display the current date, total of 10 times, with 5 seconds sleep between executions.

Here is a sample output:

This is a test in loop 1 Wed Feb 17 20:49:47 EET 2016
This is a test in loop 2 Wed Feb 17 20:49:52 EET 2016
This is a test in loop 3 Wed Feb 17 20:49:57 EET 2016
This is a test in loop 4 Wed Feb 17 20:50:02 EET 2016
This is a test in loop 5 Wed Feb 17 20:50:07 EET 2016
This is a test in loop 6 Wed Feb 17 20:50:12 EET 2016
This is a test in loop 7 Wed Feb 17 20:50:17 EET 2016
This is a test in loop 8 Wed Feb 17 20:50:22 EET 2016
This is a test in loop 9 Wed Feb 17 20:50:27 EET 2016
This is a test in loop 10 Wed Feb 17 20:50:32 EET 2016

You can change the echo and date commands with your own commands or script and change the sleep interval per your needs.

while loop Example

# while true; do echo -n "This is a test of while loop";date ; sleep 5; done

Here is sample output:

This is a test of while loopWed Feb 17 20:52:32 EET 2016
This is a test of while loopWed Feb 17 20:52:37 EET 2016
This is a test of while loopWed Feb 17 20:52:42 EET 2016
This is a test of while loopWed Feb 17 20:52:47 EET 2016
This is a test of while loopWed Feb 17 20:52:52 EET 2016
This is a test of while loopWed Feb 17 20:52:57 EET 2016

The above command will run until it is either killed or interrupted by the user. It can come in handy if you need to run a command running in the background and you don’t want to count on cron.

Important: When using the above methods, it is highly recommend that you set interval long enough to give enough time of your command to finish running, before the next execution.

Conclusion

The samples in this tutorial are useful, but are not meant to completely replace the cron utility. It is up to you to find which one works better for you, but if we have to separate the usage of both techniques, I would say this:

  1. Use cron when you need to run commands periodically even after system reboots.
  2. Use the methods explained in this tutorial for programs/scripts that are meant to run within the current user session.

As always if you have any questions or comments, do not hesitate to submit them in the comment section below.

Marin Todorov
I am a bachelor in computer science and a Linux Foundation Certified System Administrator. Currently working as a Senior Technical support in the hosting industry. In my free time I like testing new software and inline skating.

Each tutorial at TecMint is created by a team of experienced Linux system administrators so that it meets our high-quality standards.

Join the TecMint Weekly Newsletter (More Than 156,129 Linux Enthusiasts Have Subscribed)
Was this article helpful? Please add a comment or buy me a coffee to show your appreciation.

15 thoughts on “How to Run or Repeat a Linux Command Every X Seconds Forever”

  1. Is there any chance you can help me with this? It is really blowing my mind.

    I would like you to create a shell script that runs on an interval of your choosing (10 seconds, 15 seconds, 30 seconds, etc.).

    The shell script should:

    Log all processes that are running.
    If a duplicate program(s) is executed, the shell script will automatically “kill” the process associated with the second instance of that particular program.

    The script should:

    Redirect the contents of your cron table to a file (Please allow the script to run long enough to capture the data.
    You will also have to ensure some program is executed twice so the script will actually kill the process).

    This is in centos

    Reply
  2. Thanks, used this plus "$(ls | shuf -n1)" to creating random animated gifs from a folder into a little animated pixel art slideshow in my terminal.

    Reply
  3. Any idea of how to use the watch and sleep commands together?

    Like watch -n 5 "cmd1; sleep 3; cmd2"

    e.g. watch -n 5 "date; sleep 3; date"

    This doesn’t work as expected. :(

    The WAR that I have used is to move command to a script file and use it like watch -n 5 test.sh.

    Reply
  4. Oh my god, thanks a lot, i was trying to use cron, but 1 minute is too long, you saved me, a simple command that do the job, thanks a lot man

    Reply
  5. I GOT REALLY STUCK.

    I tried to follow all the instructions above to set up my LCD screen to work with my pi Model B+, but it looks like I got myself into trouble. The LCD screen won’t work– and the pi won’t book up correctly. After step 3, I rebooted the Pi, but I could get back to a working environment- meaning I can’t get to the command-line to finish up the setup process.

    Could you help me with this?

    Reply
  6. Instead of “while true; do (some command);sleep 3;done” You can just use “while sleep 3;do (some command);done”

    The sleep command returns true in a conditional.

    Reply
  7. Please how will i grep a string in a log file to output the lastest string in the file.

    Thanks for your answer as usual.

    Reply
  8. Another nice command is ‘at’ that executes the commands specified from the input stream at a given time. On Debian, it is provided by the package at.

    The nice thing about ‘at’ is that the time specification is quite flexible and intuitive
    echo notify-send Hoops | at now + 5 minute
    echo notify-send Hoops | at 10pm
    echo notify-send Hoops | at 10pm tomorrow
    echo notify-send Hoops | at 22:00 monday

    By itself t does not repeat but that can easily be done using a loop.

    for ((i=1;i<10;i++)) ; do echo echo notify-send "Hoops $i" | at now + $i minute ; done

    Be aware that 'at', like cron, executes its commands in a clean environment so without most environment variables such as DISPLAY.

    Reply

Got something to say? Join the discussion.

Thank you for taking the time to share your thoughts with us. We appreciate your decision to leave a comment and value your contribution to the discussion. It's important to note that we moderate all comments in accordance with our comment policy to ensure a respectful and constructive conversation.

Rest assured that your email address will remain private and will not be published or shared with anyone. We prioritize the privacy and security of our users.