7

in my bash script I try to use a number as an input variable for a for loop I run the script as

./script.sh InputFolder/ Number_of_iterations

the script should work inside the given folder and run a for loop as many times as the Number_of_iterations variable is set to. But somehow I can't set the variable as an integer.

this is an example of my loop in the script:

for i in {1..$(($2))}
do
 echo "Welcome $i times"
done

I have tried already the double brackets $(($...)) option as well as the double quotations "...", but the output I keep getting is

Welcome {1..5} times

which make me think, this is not an integer. I would appreciate any help in reading the input parameter as an integer into the script.

Kusalananda
  • 333,661

2 Answers2

11

You can do this two ways:

With ksh93-compatible shells (ksh93, zsh, bash):

for (( i=1;i<=$2;i++ ))
do
 echo "Welcome $i times"
done

Here we set i to 1 and loop, incrementing it until it is less than or equal to $2, outputting:

Welcome 1 times
Welcome 2 times

With POSIX shells on GNU systems:

for i in $(seq "$2")
do
 echo "Welcome $i times"
done

The seq command (GNU specific) will output numbers from 1 to the number specified in $2 on separate lines. Assuming you've not modified $IFS (which by default contains the line delimiter character), the command substitution will split that into as many elements for for to loop on.

3

In Bash this construct that you're trying to use: {1..$(($2))} or {1..$2} is the brace expansion. The reason why it doesn't work for you is that in the order of shell expansions the brace expansion is the first one. So when this expansion takes place $2 is still only $2, not 5 as you'd like. The brace expansion doesn't work then. It simply produces 1..$2, and then when it's time to expand $2, the shell does so, and you're left with this one word:

{1..5}

The braces are still there because they have not been consumed by the brace expansion.

As for solutions, see Raman Sailopal's answer.