0

I am trying to fetch the for loop limit from the user. When I am passing that variable it's not iterating across it

for num in {1..$totalNodes}

But when I am giving a hardcoded value

for num in {1..10}

it runs fine. Can anyone please help.

Here is my code:

#!/bin/bash
#!/bin/sh
read -p "Enter the total no of nodes : " totalNodes
read -p "Enter the no of Master nodes : " masterNodes

echo $totalNodes
echo $masterNodes

for num in {1..5}
    do
        echo "$num"

        read -p "Enter the Node $num IP : " node[$num]

    done

echo $node
Arjun Mathew Dan
  • 5,240
  • 1
  • 16
  • 27
  • here is my script : #!/bin/bash #!/bin/sh read -p "Enter the total no of nodes : " totalNodes read -p "Enter the no of Master nodes : " masterNodes echo $totalNodes echo $masterNodes for num in {1..5} do echo "$num" read -p "Enter the Node $num IP : " node[$num] done echo $node – vikram keshari Mar 22 '17 at 06:57
  • This may not be an explicit duplicate, OP has got the logic right, it is just the issue with the brace expansion that is the heart of the problem. – Inian Mar 22 '17 at 09:26

1 Answers1

1

The problem with brace-expansion is it happens before everything else, so that the parameter expansion you are expecting to happen(expansion of variable totalNodes does not happen during that expansion. See from the man bash page,

EXPANSION

Expansion is performed on the command line after it has been split into words. There are seven kinds of expansion performed: brace expansion, tilde expansion, parameter and variable expansion, command substitution, arithmetic expansion, word splitting, and pathname expansion.

The order of expansions is: brace expansion; tilde expansion, parameter and variable expansion, arithmetic expansion, and command substitution (done in a left-to-right fashion); word splitting; and pathname expansion.

So you will not get to what you are trying to achieve. Since you are in bash you can use the C style for-loop iteration, as

read -p "Enter the total no of nodes : " totalNodes
for (( i=1; i<=totalNodes; i++)); do
    printf "%d\n" "$i"
done
Inian
  • 80,270
  • 14
  • 142
  • 161