How to Use a Shell Variable in a For Loop?

April 3, 2026 3 answers
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

purl2.knit
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.

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!

Reply to this answer
!checkmate soon+
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
rope+pulley
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.

Related Discussions