bash variables in for loop range

Yes, that's because brace-expansion occurs before parameter expansion. Either use another shell like zsh or ksh93 or use an alternative syntax:

Standard (POSIX) sh syntax

i=1
while [ "$i" -le "$number" ]; do
  echo "$i"
  i=$(($i + 1))
done

Ksh-style for ((...))

for ((i=1;i<=number;i++)); do
  echo "$i"
done

use eval (not recommended)

eval '
  for i in {1..'"$number"'}; do
    echo "$i"
  done
'

use the GNU seq command on systems where it's available

unset -v IFS # restore IFS to default
for i in $(seq "$number"); do
  echo "$i"
done

(that one being less efficient as it forks and runs a new command and the shell has to reads its output from a pipe).

Avoid loops in shells.

Using loops in a shell script are often an indication that you're not doing it right.

Most probably, your code can be written some other way.


You don't even need a for loop for this, just use the seq command:

$ seq 100

Example

Here's the first 10 numbers being printed out:

$ seq 100 | head -10
1
2
3
4
5
6
7
8
9
10

You can use the following:

for (( num=1; num <= 100; num++ ))
do
    echo $num
done

Tags:

Bash

For