MuscleUpUp
MuscleUpUp

Reputation: 131

How to execute bash script in a loop which iterations will be written from a keyboard

I have a bash script which tests funcionality of the program. I run this script simply by using ./name_of_script. But I want to have a opportunity to add number of iterations in the same command, like this:

./name_of_script number_of_iterations

Moreover, if the number_of_iterations won't be written in a command, it should be equal 1 by default.

I write some code but it doesnt work as good as I want.

read iterations 

for(( w=1; w <= iterations; w++))
do
.
.
.
done

It doesnt provide determination of iterations in one command and waits for me to write it in a second line. Thanks for any help.

Upvotes: 1

Views: 29

Answers (1)

Florian Schlag
Florian Schlag

Reputation: 659

You can do it like this:

#!/bin/bash
iterations=${1:-1}
#            ^  ^
#            |  |-----------
#            |             |
#      First parameter     Default if first parameter is unset
for(( w=1; w <= iterations; w++))
do
    echo "Hello World $w"
done

Upvotes: 1

Related Questions