How to Use a Shell Variable in a For Loop?

0
10
Asked By CuriousCoder42 On

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

Answered By TechSavvy92 On

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!

Answered By ShellMaster99 On

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.

Answered By NewbieNinja On

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.

HelpfulHacker -

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

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.