bash variables in for loop range

All we need is an easy explanation of the problem, so here it is.

I want to print list of numbers from 1 to 100 and I use a for loop like the following:

number=100
for num in {1..$number}
do
  echo $num
done

When I execute the command it only prints {1..100} and not the list of number from 1 to 100.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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.

Method 2

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

Method 3

You can use the following:

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

Method 4

The brace expansion only works for literal integers or single characters. It happens before variable expansion, so you cannot use variables in it.

Method 5

Also there is a pre increment.

for (( int=1; int <= 100; ++int));
  do
    printf '%s ' $int
  done

Use printf to print the numbers in one row instead.

Another example to increment by 2

for (( int=1; int <= 100; int+=2));
  do
    printf '%s ' $int
  done

Method 6

Another way to do it simply in Bash script (and that looks like what you were doing)

number=100
for num in $(seq 1 $number); do
    echo $num;
done

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply