Linux: Repeat Command N Times – Bash FOR Loop

Sometimes you might need to run some command from the Linux command line and repeat it several times.

There is a simple way to write a command once and have it executed N times using Bash loop FOR.

In this short note you’ll find how to execute some command a number of times in a row.

The best way to run a command N times is to use loop FOR in Bash.

Cool Tip: The same loop can be used for a mass mail sending! Send bulk emails from the Linux command line to test your mail server! Read more →

Repeat a Command Multiple Times in Linux

Use the following syntax to run some command 5 times:

for n in {1..5}; do <COMMAND>; done

Let’s help Bart Simpson to fill a chalkboard:

$ for n in {1..5}; do echo "I WILL NOT SKATEBOARD IN THE HALLS"; done
I WILL NOT SKATEBOARD IN THE HALLS
I WILL NOT SKATEBOARD IN THE HALLS
I WILL NOT SKATEBOARD IN THE HALLS
I WILL NOT SKATEBOARD IN THE HALLS
I WILL NOT SKATEBOARD IN THE HALLS

Cool Tip: Run commands on a remote Linux server over SSH and get the results locally! Read more →

If you often need to use such construction from the Linux command line, you can create the following Bash function (add to your ~/.bashrc):

function run() {
    number=$1
    shift
    for n in $(seq $number); do
      $@
    done
}

Usage:

$ run 5 <COMMAND>

Cool Tip: Every Linux administrator must know how to read a file line by line with a Bash WHILE loop! Read more →

Example:

$ run 5 echo "I WILL NOT SKATEBOARD IN THE HALLS"
I WILL NOT SKATEBOARD IN THE HALLS
I WILL NOT SKATEBOARD IN THE HALLS
I WILL NOT SKATEBOARD IN THE HALLS
I WILL NOT SKATEBOARD IN THE HALLS
I WILL NOT SKATEBOARD IN THE HALLS
0 (0)
Article Rating (No Votes)
Rate this article
Attachments
There are no attachments for this article.
Comments
There are no comments for this article. Be the first to post a comment.
Full Name
Email Address
Security Code Security Code
Related Articles RSS Feed
Usuwanie spacji z zmiennych w bash
Viewed 2558 times since Tue, May 22, 2018
The Ultimate Bash Array Tutorial with 15 Examples
Viewed 13519 times since Sun, Sep 30, 2018
Using Shell Redirection: All About the Here-Doc
Viewed 10496 times since Wed, May 30, 2018
Script HW/SW AIX
Viewed 9319 times since Mon, Jun 4, 2018
Transform XML to CSV Format | Unix String Pattern Manipulation The Ugly Way
Viewed 5741 times since Sun, Jan 9, 2022
O’Reilly’s CD bookshelf
Viewed 12975 times since Wed, Jun 27, 2018
“Yes/No” in Bash Script – Prompt for Confirmation
Viewed 32806 times since Mon, Feb 18, 2019
Display basic information about Physical Volumes
Viewed 3532 times since Sun, Jun 3, 2018
30 Handy Bash Shell Aliases For Linux / Unix / MacOS
Viewed 4909 times since Thu, Feb 11, 2021
Linux / UNIX: Convert Epoch Seconds To the Current Time
Viewed 3121 times since Fri, May 25, 2018