1

Possible Duplicate:
How do I iterate over a range of numbers in bash?

I am trying to print "Hello World!" 10 times via the code below, but it is printed only one time. Where am I missing the correct syntax?

RUNS=10

for RUN in {1..$RUNS}
do
    echo "Hello World!"
done
Community
  • 1
  • 1
Moeb
  • 10,527
  • 31
  • 84
  • 110

3 Answers3

2

This question contains all the answers you need

In brief, I would suggest you to use:

RUNS=10
for RUN in $(seq 1 $RUNS)
do
    echo "Hello World!"
done

since it will more likely work on other shells too.

If you want to avoid the overhead of the subshell, you can use:

RUNS=10
i=0;
while [ $i -lt $RUNS ]
do
    echo "Hello World!"
    i=$(($i+1))
done
Community
  • 1
  • 1
mrucci
  • 4,342
  • 3
  • 33
  • 35
  • this fragment spawns child process _seq_, quite an overhead for a simple for-loop – bobah Nov 06 '12 at 08:38
  • That's the way to do it for maximum compatibility with POSIX shell. Have a look [here](https://wiki.ubuntu.com/DashAsBinSh) and [here](http://mywiki.wooledge.org/Bashism) for other forms of bashisms. – mrucci Nov 06 '12 at 08:46
  • this question is about Bash, neither about POSIX shell, nor about compatibility with POSIX shell – bobah Nov 06 '12 at 08:50
  • 1
    Absolutely. Also the question is not a about performance... – mrucci Nov 06 '12 at 09:00
2

You want to do a brace expansion, but bash does not do double-expansion (it needs to expand $RUNS). You can force double-expansion by

for RUN in $(eval echo {1..$RUNS})
do 
    echo "Hello World!"
done

But I suggest you avoid this mess like the plague and just do

for RUN in $(seq 1 $RUNS) 
do 
    echo "Hello World!"
done

or

for ((RUN=1; RUN<RUNS; RUN++))
do 
    echo "Hello World!"
done
choroba
  • 231,213
  • 25
  • 204
  • 289
Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
0

{A..B} syntax does not seem to be substituting variables

for ((i=0; i < $RUNS; ++i)); do echo "hello world"; done
bobah
  • 18,364
  • 2
  • 37
  • 70
  • 1
    More specifically, brace expansion occurs before parameter expansion. As brace expansion requires constants, the whole construct is treated as a single string rather than being expanded. – chepner Nov 06 '12 at 13:15