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.
Yes, that's because brace-expansion occurs before parameter expansion. Either use another shell like zsh
or ksh93
or use an alternative syntax:
i=1
while [ "$i" -le "$number" ]; do
echo "$i"
i=$(($i + 1))
done
for ((...))
for ((i=1;i<=number;i++)); do
echo "$i"
done
eval
(not recommended)eval '
for i in {1..'"$number"'}; do
echo "$i"
done
'
seq
command on systems where it's availableunset -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).
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.
ls
... do something for that name.
while read
instead of sed/awk/…, or looping over the output of find
instead of using -exec
. But a blanket “avoid loops in shells” is going too far.
Commented
Apr 25, 2015 at 23:40
while read
loop is perfectly fine.
Commented
Oct 24, 2015 at 23:05
You don't even need a for loop for this, just use the seq
command:
$ seq 100
Here's the first 10 numbers being printed out:
$ seq 100 | head -10
1
2
3
4
5
6
7
8
9
10
seq $number
if you want to assign some integer to $number
.
Commented
Apr 4, 2023 at 23:59
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
The brace expansion only works for literal integers or single characters. It happens before variable expansion, so you cannot use variables in it.
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