Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for loops with variables in range won't work

Tags:

bash

shell

So I was writing a for loop and getting some errors, to get an understanding of the errors I wrote this

    #! /bin/bash
    b=${1:- 10}
    echo $b
    for i in {0..$b}
    do
            echo "$i"
    done

so if I run ./forloop.sh 10

I get

    10
    {0..10}

why doesn't the range work when I have a variable as the second argument?

like image 939
Jake Schievink Avatar asked Dec 31 '25 13:12

Jake Schievink


2 Answers

Bash doesn't expand the range. Use this instead.

for (( i=0; i<=$b; i++)) 
like image 143
FDinoff Avatar answered Jan 02 '26 14:01

FDinoff


The part of bash that expands things like {1..10} into 1 2 3 4 5 6 7 8 9 10 runs before any parameters like $b are replaced by their values. Since {1..$b} doesn't look like a numeric range, it doesn't get expanded. By the time parameter expansion turns it into {1..10}, it's too late; nothing is going to come along and evaluate the curly-brace expression.

like image 21
Mark Reed Avatar answered Jan 02 '26 15:01

Mark Reed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!