Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a bash for-loop with a variable top-end

I frequently write for-loops in bash with the well-known syntax:

for i in {1..10}  [...]

Now, I'm trying to write one where the top is defined by a variable:

TOP=10
for i in {1..$TOP} [...]

I've tried a variety of parens, curly-brackets, evaluations, etc, and typically get back an error "bad substitution".

How can I write my for-loop so that the limit depends on a variable instead of a hard-coded value?

like image 623
abelenky Avatar asked Mar 19 '12 22:03

abelenky


2 Answers

You can use for loop like this to iterate with a variable $TOP:

for ((i=1; i<=$TOP; i++))
do
   echo $i
   # rest of your code
done
like image 153
anubhava Avatar answered Nov 15 '22 21:11

anubhava


If you have a gnu system, you can use seq to generate various sequences, including this.

for i in $(seq $TOP); do
    ...
done
like image 24
Kevin Avatar answered Nov 15 '22 20:11

Kevin