This question already has an answer here:

I am trying to do a simple script which runs a few commands N number of times, determined by the user's input. However, when it comes to run the commands (in a for loop) - The variable is ignored:

read -p "Please enter the number of times you wish to fail over: " num


  for run in {1..$num}
   do echo "STOP: "
   systemctl stop $broker
   sleep $st
   echo "START: "
   systemctl start $broker
   sleep $st
+ '[' y == n ']'
+ '[' y == N ']'
+ for run in '{1..$num}'
+ echo 'STOP: '
+ date
Tue Dec  4 16:14:11 GMT 2018

Can anyone explain why this is happening and what I need to do to rectify? Or does anyone have a better method for this?

marked as duplicate by Jeff Schaller, Rui F Ribeiro, Christopher, RalfFriedl, G-Man Dec 4 '18 at 21:20

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 2
    (short version: brace expansion happens before variable/parameter expansion) – Jeff Schaller Dec 4 '18 at 16:21

Just a collection of - more or less secure - and possibly well known approaches:

eval "for i in {1..$a}; do echo \$i; done"
cat <<< "for i in {1..$a}; do echo \$i; done" | bash
echo "for i in {1..$a}; do echo \$i; done" | bash
for i in $(seq 1 $a); do echo $i; done

Not the answer you're looking for? Browse other questions tagged or ask your own question.