tags:

views:

78

answers:

6

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?

+4  A: 
for ((n=0;n<10;n++)); do some_command; done
BatchyX
+6  A: 
for run in {1..10}
do
  command
done
Joe Koberg
If you have LOTS of iterations, the form with `for (n=0;n<k;n++))` may be better; I suspect `{1..k}` will materialize a string with all those integers separated by spaces.
Joe Koberg
@Joe Koberg, thanks for the tip. I'm typically use N<100 so this seems good.
bstpierre
Accepting this as the answer since it is slightly more concise (by a whisker) than `for(())`.
bstpierre
@bstpierre: The brace expansion form can't use variables (easily) to specify the range in Bash.
Dennis Williamson
That is true. Brace expansion is performed before variable expansion according to http://www.gnu.org/software/bash/manual/bashref.html#Brace-Expansion , thus it will never see the values of any variables.
Joe Koberg
@Dennis Williamson - Thanks for the warning, and for your answer below. 99% of the time I won't need to worry about it.
bstpierre
A: 

How about the alternate form of for mentioned in (bashref)Looping Constructs?

SamB
throw him a bone and give an example of the alternate form?
Joe Koberg
It's in BatchyX's answer already
bstpierre
A: 

For one, you can wrap it up in a function:

function manytimes {
    n=0
    times=$1
    shift
    while [[ $n -lt $times ]]; do
        $@
        n=$((n+1))
    done
}

Call it like:

$ manytimes 3 echo "test" | tr 'e' 'E'
tEst
tEst
tEst
bta
+1  A: 

Another form of your example:

n=0; while (( n++ < 10 )); do some_command; done
Dennis Williamson