0

Here is my code

bash-3.2$ read num
100
bash-3.2$ for k in {1..$num}
> do
>    echo Printed $k times
> done
{1..100}
bash-3.2$ echo $num
100
bash-3.2$ echo $k
{1..100}

Does anyone have any idea why it is doing this? It isn't the variable num that's wrong because I checked that with my echo at the end.

4 Answers4

0

The for .. in .. construct is for looping through lists of strings, not looping a number of times. You want the for (( expr1 ; expr2 ; expr3 )) construct. Try this:

for (( i = 1 ; i <= $num ; ++ i )) ; do
  echo Next: $i
done
Paul Hicks
  • 12,373
  • 4
  • 45
  • 72
  • This works to :) It's just the approved answer sounds more like my java syntax, so is the one I'll probably be using more, nevertheless I +1'd your post –  Feb 04 '14 at 04:56
0

how about this;

for k in $(seq 1 $num)
do 
  echo Printed $k times
done
chepner
  • 446,329
  • 63
  • 468
  • 610
BMW
  • 38,908
  • 11
  • 90
  • 109
0

you can try:

for k in $(seq $num)
do 
  echo Printed $k times
done
MLSC
  • 5,584
  • 7
  • 49
  • 85
-1

Try this, for some reason that doesn't work as syntax...

bash-3.2$ read k
100
bash-3.2$ read i
1
bash-3.2$ for (( c=$i; c<=$k; c++ ))
> do
>     echo -n "Printed $k times"
>     sleep 1
> done
Printed 1 times
Printed 2 times
...
Printed 99 times
Printed 100 times

Click here for more on for syntaxes in scripting languages.

A.J. Uppal
  • 18,339
  • 6
  • 41
  • 73
  • The reason is that brace expansion occurs before parameter expansion; brace expansion requires literal values. – chepner Feb 04 '14 at 14:52