bash variables in for loop range

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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


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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x