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

17,524

Solution 1

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

Solution 2

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

for i in $(seq $TOP); do
    ...
done

Solution 3

Answer is partly there : see Example 11-12. A C-style for loop.

Here is a summary from there, but be aware the final answer to your question depends on your bash interpreter (/bin/bash --version):

# Standard syntax.
for a in 1 2 3 4 5 6 7 8 9 10

# Using "seq" ...
for a in `seq 10`

# Using brace expansion ...
# Bash, version 3+.
for a in {1..10}

# Using C-like syntax.
LIMIT=10
for ((a=1; a <= LIMIT ; a++))  # Double parentheses, and "LIMIT" with no "$".

# another example
lines=$(cat $file_name | wc -l)
for i in `seq 1 "$lines"`

# An another more advanced example: looping up to the last element count of an array :
for element in $(seq 1 ${#my_array[@]})
Share:
17,524
abelenky
Author by

abelenky

I've worked in C, C++, C#, ASP.net, Python and touched on many other languages. Graduated from MIT in '96 in Computer Science, active in politics. At various times, worked for Microsoft, Tegic, AOL, Melodeo, Sagem-Morpho, and (secret project). Currently a Senior Engineer at Spear Power. DOGE: D5VYb9M5TYmPNR86LNiV1PAjL3JxW3Hyeu

Updated on June 12, 2022

Comments

  • abelenky
    abelenky almost 2 years

    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?

  • Daenyth
    Daenyth about 12 years
    seq is not recommended over brace expansion. The behavior between bsd/gnu isn't quite the same.
  • Kevin
    Kevin about 12 years
    @daenyth good to note for when brace expansion is a viable alternative, but the whole point of this question is that brace expansion doesn't work with variable bounds.