-1

I'm having a hard time figuring out how to use a $var inside curly braces {}..

#!/bin/bash
read -p "How many files must there be built?" numb
for n in {1..$numb}
do
    echo "Building file $n"
    touch file$n.txt
done

This would result in:

How many files must there be built?8
Building file {1..8}

I've tried enclosing the $numb inside backticks or double quotes but to no avail..

1 Answers1

0

You could use this syntax for your loop:

#!/bin/bash
read -p "How many files must there be built?" numb
for ((i=1; i<=$numb; i++)); do
    echo "Building file $i"
    touch file$i.txt
done

It's less fancy, but it works.

  • You don't need the `$` sign inside the math `(())` operator. – accdias Oct 21 '21 at 18:29
  • 2
    In [How to Answer](https://stackoverflow.com/help/how-to-answer), see the section _Answer Well-Asked Questions_, and therein the bullet point regarding questions that "have been asked and answered many times before" – Charles Duffy Oct 21 '21 at 18:32
  • Indeed, the question was already asked before and had 5 upvoted answers already, including the solution you mention (see [this answer](https://stackoverflow.com/a/9337541/10669875). It's better to avoid duplicate answers. The other question contains all solutions at one place, which is more convenient than having to browse multiple questions to find the best answer. – wovano Oct 21 '21 at 18:36
  • Less fancy, *and* better performing. The brace expansion is fully expanded before the loop begins; the C-style loop only sets `i` on demand, so there's a drastic difference between the two when `numb` is large. – chepner Oct 21 '21 at 19:33