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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, chepner. That solves my problem and provides a bit of background with respect to why this behavior is expected.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.