Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash variable for upper limit of for loop number syntax [duplicate]

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?

like image 314
JawguyChooser Avatar asked Feb 09 '26 17:02

JawguyChooser


1 Answers

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.

like image 149
chepner Avatar answered Feb 12 '26 14:02

chepner