Bash – How to create a for loop with a changeable number of iterations

bashforshell-script

How do you iterate through a loop n amount of times when n is specified by the user at the beginning?

I have written a shell script and need to repeat a certain part of it n numbers of times (depending upon how many times the user wishes).

My script so far looks like this:

echo "how many times would you like to print Hello World?"
read num
for i in {1.."$num"}
do
echo "Hello World"
done

If I change "num" to a number such as "5" the loop works however I need to be able to let the user specify the amount of times to iterate through the loop.

Best Answer

You can use seq

for i in $(seq 1 "$num") 

or your shell may support C-style loops e.g. in bash

for ((i=0; i<$num; i++))
Related Question