I'm trying to use a for loop in Bash to iterate over a range defined by a variable. When I run this loop with braces:
```
for i in {1..$len} ; do
echo $i
done
```
It just prints `{1..13}` instead of iterating. Is there a way to incorporate a variable within the braces for the loop?
3 Answers
Unfortunately, you can't directly use a variable in brace expansions in Bash—those expand before any variables do. A better way to loop is to use a C-style for loop like this:
```
for ((i=1; i<=len; i++)); do
echo "$i"
done
```
This approach works perfectly!
You could use the `seq` command for a similar result:
```
for i in `seq $len`; do
echo "$i"
done
```
But keep in mind that this might be less efficient because it creates a separate process for `seq`. The C-style loop is often simpler and more efficient.
Just to clarify, because brace expansion is the first thing Bash does, it doesn't recognize the `$len` variable at that point. You're better off stick with the C-style loop or even `seq` if you want a cleaner syntax.

Right! I couldn't figure out why the variable wasn’t being evaluated at first—glad we’re on the same page!