Linux / UNIX: Run Command a Number of Times In a Row

Posted on in Categories last updated May 27, 2011

How do I run “foo” command 10 times (or n times) under Linux or UNIX like operating systems?

You can use bash shell loop (run code or command repeatedly) to run a command 10 times as follows:

for i in {1..10}; do commandNameHere; done

For example, run UNIX date command five times, enter:

for i in {1..5}; do date; done

You can also use c like bash for loop syntax:

for ((n=0;n<5;n++))
do
 command1
 command2
done

The for loop syntax for tcsh / csh / ksh and other shell may changes from version to version. You can use python or Perl as follows to run date command 5 times:

#!/usr/bin/perl
for $i (1 .. 5) {
   system("date");
}

Python example:

#!/usr/bin/python
# Run unix date command 3 times 
import os;
for x in range(0,3):
    os.system("date")

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

9 comment

  1. Nice and useful article, indeed.
    A litte note:

    You said “For example, run UNIX date command five times, enter:”

    and then shows: for i in {1..10}; do date; done

    I mean: five times would be

    for i in {1..5}; do date; done

    But I know people understood what you’ve said.
    Thanks again!

  2. Moin,

    old style methods:

    for i in $(seq 5);do date;done
    for i in `seq 1 5`;do date;done
    for i in 1 2 3 4 5;do date;done
    for i in a b c d orwhatever;do date;done

    at last some crazy unuseful (only work with dirs with more than 5 items)

    for i in `ls /proc/*|head -n5`;do date;done

  3. Hi.

    I got this little function in my bash_aliases:
    repeat() { local i n; n=$1; shift; for ((i=1; i<=n; i++)); do "$@"; done; }

    then you can do # repeat 5 echo hey there

Leave a Comment