4

The following bash script

#!/bin/bash

startNumber=$(( 1 ))
endNumber=$(( $startNumber + 3 ))

#for number in {$startNumber..$endNumber}
for number in {1..4}
do
        echo $number
done

exit 0

gives the desired output

1
2
3
4

However, when I switch the uncommented and commented for loop, the output is

{1..4}

What am I doing wrong?

Kusalananda
  • 320,670
  • 36
  • 633
  • 936
Andrej
  • 143
  • 5
  • 3
    See [Can I use variables inside {} expansion without `eval`?](https://unix.stackexchange.com/questions/117144/can-i-use-variables-inside-expansion-without-eval) – steeldriver Nov 13 '20 at 13:21
  • Right, I edited it. Thanks, I'll have a look at it. So my first impression is that I can't do this elegantly and should do the for loop as @jesse_b suggested? – Andrej Nov 13 '20 at 13:27
  • 1
    @Andrej: What is wrong with the c style for loop? It's clean (would be a lot cleaner if you didn't use camel case variable names), and arguably more efficient. – jesse_b Nov 13 '20 at 13:29

2 Answers2

8

Variables won't expand inside brace expansion. You could do:

for ((number=startNumber; number<=endNumber; number++)); do
    echo "$number"
done

Also, there is no reason to use arithmetic expansion for startNumber you should simply do:
startNumber=1.

Additionally, you don't need to use $ to expand variables inside arithmetic expansion, so endNumber could be:
endNumber=$((startNumber+3))

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
jesse_b
  • 35,934
  • 12
  • 91
  • 140
8

As explained elsewhere the expansion won't work. Alternative way to get your sequence of numbers:

for number in $(seq $startNumber $endNumber)
do
  echo $number
done
bxm
  • 4,561
  • 1
  • 20
  • 21