Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to run a command N times in bash?

Tags:

bash

loops

I occasionally run a bash command line like this:

n=0; while [[ $n -lt 10 ]]; do some_command; n=$((n+1)); done 

To run some_command a number of times in a row -- 10 times in this case.

Often some_command is really a chain of commands or a pipeline.

Is there a more concise way to do this?

like image 605
bstpierre Avatar asked Sep 17 '10 17:09

bstpierre


People also ask

How do I make my bash script run faster?

There are few ways to make your shell (eg Bash) execute faster. Try to use less of external commands if Bash's internals can do the task for you. Eg, excessive use of sed , grep , awk et for string/text manipulation. If you are manipulating relatively BIG files, don't use bash's while read loop.


2 Answers

If your range has a variable, use seq, like this:

count=10 for i in $(seq $count); do     command done 

Simply:

for run in {1..10}; do   command done 

Or as a one-liner, for those that want to copy and paste easily:

for run in {1..10}; do command; done 
like image 72
Joe Koberg Avatar answered Sep 20 '22 16:09

Joe Koberg


Using a constant:

for ((n=0;n<10;n++)); do     some_command;  done 

Using a variable (can include math expressions):

x=10; for ((n=0; n < (x / 2); n++)); do some_command; done 
like image 35
BatchyX Avatar answered Sep 23 '22 16:09

BatchyX