0

If I print out a loop with fixed values like so:

for i in L0{1..4}
do
    echo $i
done

I get the desired output:

L01
L02
L03
L04

However, if I try to use a variable:

for i in L0{1..${num_lanes}}
do
    echo $i
done 

I get:

L0{1..4}

How can I use a variable within curly braces?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
user483292
  • 61
  • 6
  • When you run `sh`, that causes your shebang specifying bash to be ignored. If you want your code to run with bash, you need to run bash, not sh. – Charles Duffy Jan 18 '23 at 04:26
  • And brace expansion has never worked with variables even in bash. Braces get expanded **before** variables are expanded, so you can't use a variable to determine what brace expansion will do. – Charles Duffy Jan 18 '23 at 04:27
  • 3
    The answer is "you can't" (without insecure dirty hacks). Bash doesn't support it. – Charles Duffy Jan 18 '23 at 04:30
  • 3
    See also [BashPitfalls #33](https://mywiki.wooledge.org/BashPitfalls#for_i_in_.7B1...24n.7D) – Charles Duffy Jan 18 '23 at 04:30
  • 1
    `for ((i=1; i<=num_lanes; i++)); do echo "L0$i"; done` – Charles Duffy Jan 18 '23 at 04:32
  • 1
    Provided that you know for sure that `num_lanes` contains a number, `for i in $(eval "echo L0{1..$num_lanes}");` should do, but a counting loop, as Charles Duffy suggests, is IMO clearer. – user1934428 Jan 18 '23 at 08:35
  • 1
    Brace expansion happens before any other expansion (like parameter expansion, as you would need here); see 4th para in the [manual](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html) – suvayu Jan 18 '23 at 10:07

0 Answers0