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.
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
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
seq 1 $number
and it is working in bash. – Vombat Aug 26 '13 at 12:15ls
... do something for that name. – 0fnt Sep 13 '14 at 16:19while read
instead of sed/awk/…, or looping over the output offind
instead of using-exec
. But a blanket “avoid loops in shells” is going too far. – Gilles 'SO- stop being evil' Apr 25 '15 at 23:40while read
loop is perfectly fine. – Gilles 'SO- stop being evil' Oct 24 '15 at 23:05