How to Use a Shell Variable in a For Loop?
Asked by
cutSpeed-B8
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?
Answers
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.
Reply to this answer
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.
Reply to this answer
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!
Reply to this answer
Add your answer
Answers are reviewed before publication.
just here for answers: Right! I couldn't figure out why the variable wasnโt being evaluated at firstโglad weโre on the same page!