0

when I populate an array using explicit range value it get populated correctly using the code below:

arr=()
for i in {0..10}
do
    arr+=( 1 )
done
echo ${arr[@]}

and I got the following output output (nothing surprising)

However, when storing the range in a variable and calling it as in the code below it only shows one element:

range=10
arr=()
for i in {0..$range}
do
    arr+=( 1 )
done
echo ${arr[@]}

I got the following output error output

danix
  • 135
  • 1
  • 9

1 Answers1

1

Variable expansion does not occur before brace expansion so you only get a literal {0..1} as a single iterated argument.

Use the old school method instead:

for (( i = 0; i <= range; ++i )); do
  • Used <= here because .. is inclusive.
konsolebox
  • 72,135
  • 12
  • 99
  • 105
  • Just out of curiosity, why did you decide to answer this instead of marking it as a duplicate since your explanation is also mentioned in the question I linked. – 0stone0 Jan 05 '22 at 12:27
  • @0stone0 I didn't look at it before I answered and it's trivial enough that I can simply give a solution specific to the example in the question. – konsolebox Jan 05 '22 at 12:30