Bash for loop with a variable

Asked by At

I'm trying to write a for loop in bash so that I can iterate numbers from 1 to a number larger than 10. In the cases where the number has only one digit, a zero should be added to its left (as in 01).

The solution I found for that was this:

for i in 0{1..9} {10..43}; do
        echo "stuff$i.txt"
done

This works, but I wanted to have the upper limit as a variable, so I tried this:

max_test=43

for i in 0{1..9} {10..$max_test}; do
        echo "stuff$i.txt"
done

When running this, the script prints out

stuff01.txt

stuff02.txt

...

stuff09.txt

stuff{10..43}.txt

I found this answer, but in my situation I'd need 2 for loops due to that one-digit number condition. What is the best way to do what I want?

Thank you in advance

1 Answers

1
mickp On Best Solutions

You can't use a variable in brace expansion because brace expansion is done before variable expansion. You can use seq for example:

max=43
seq -w 1 "$max"