I was just wondering if it is possible to use variables in for loops?? I tried:

for number in { eval echo {0..$1}}
    echo 5

I meant for it to print out 5 the number of times I entered into the prompt however, it acts strangely if I enter in:

./test.sh 2

It should print out 5 two times, but it prints out 5 four times. Can someone help me with this? And also why is it printing out 4 times instead of 2??

Edit: For the most part

for number in $(seq "$2")

Works but If I try a calculation with it, it breaks my code:

for number in $(seq "$2")
    echo "$time + $total" | bc

Gives: seq: invalid floating point argument: ‘’ Try 'seq --help' for more information. Can someone tell me how to fix it??

  • Use backtics (`) instead of the outer { } and your loop should work, but start at 1 instead of 0 for your expected two times through the loop.
    – ubfan1
    Jul 1 at 23:54
  • If you use seq "$2" then you need to provide a numeric 2nd positional parameter when you call the script ex. ./test.sh foo 2 Jul 2 at 3:12

It prints out 5 four times because { eval echo {0..2}} results in four whitespace-separated tokens {, 0, 1 and 2}

If you want to use $1 as the end of a range expression in bash, it's better to use the external seq command:

for number in $(seq "$1")

or use a C-style for loop

for ((number=0; number<"$1"; number++))
  • It works but If I use variables inside of the for loop it breaks immediately Jul 2 at 2:09
  • time=1 total=5 for number in $(seq "$2") do echo "$time + $total" | bc done Jul 2 at 2:09
  • @YunfeiChen fails how, exactly? How are you calling the script? In particular, how many positional parameters are you supplying (since you apparently changed $1 to $2) Jul 2 at 2:15
  • Gives me:(standard_in) 1: syntax error (standard_in) 1: illegal character: : (standard_in) 1: syntax error (standard_in) 1: syntax error (standard_in) 1: syntax error (standard_in) 2: syntax error (standard_in) 2: illegal character: : (standard_in) 2: syntax error (standard_in) 2: syntax error (standard_in) 2: syntax error Jul 2 at 16:56
  • @YunfeiChen comments are not the right place for follow-on questions - in particular, the formating doesn't allow me to see what you are actually typing. If the "illegal character" is ^M then that's because your script has Windows line endings. Jul 2 at 17:21

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