Monday, April 23, 2012

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

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")
 

No comments:

Post a Comment