3

If I create a bash loop like this, using literal numbers, all works as expected:

#!/bin/bash
for i in {1..10};  do
  echo $i 
done

The output is:

1
2
3
4
5
6
7
8
9
10

But if I want to use the upper limit in a variable, I can't seem to get it it right. Here are my four attempts:

#!/bin/bash
n=10

for i in {1..$n};  do
  echo $i 
done

for i in {1.."$n"}; do 
  echo $i
done

for i in {1..${n}};  do
  echo $i 
done

for i in {1.."${n}"};  do
  echo $i 
done

And the output is now:

{1..10}
{1..10}
{1..10}
{1..10}

Not what I wanted... :(

To be clear about the question:

How do I use a variable as the limit for the range syntax in a bash for loop?

JawguyChooser
  • 1,816
  • 1
  • 18
  • 32

1 Answers1

11

Don't use {...}; use a C-style for loop.

for ((i=1; i <= $n; i++)); do

Brace expansion occurs before parameter expansion, so you can't generate a variable-length sequence without using eval. This is also more efficient, as you don't need to generate a possibly large list of indices before the loop begins.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • Thanks, chepner. That solves my problem and provides a bit of background with respect to why this behavior is expected. – JawguyChooser Jan 18 '16 at 18:55