62

I have the following code in an .sh file:

for num in {1..10}
do
  echo $num
done

Which should print numbers from 1 to 10. But, this is what I get:

{1..10}

Also, using C-like sytax doesn't work either:

for ((i=1; i<=10; i++))

This gets me an error:

Syntax error: Bad for loop variable

The version of bash that I have is 4.2.25.

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
sodiumnitrate
  • 2,899
  • 6
  • 30
  • 49

1 Answers1

102

The code should be as follows (note the shebang says bash, not sh):

#!/bin/bash
echo "Bash version ${BASH_VERSION}..."
for i in {1..10}
do
    echo "Welcome $i times"
done

You can use {0..10..1} if you want to start from 0.

Source: http://www.cyberciti.biz/faq/bash-for-loop/.

mrts
  • 16,697
  • 8
  • 89
  • 72
Pradheep
  • 3,553
  • 1
  • 27
  • 35
  • 6
    This: (note the shebang says bash, not sh) – Jon Kiparsky Jul 19 '13 at 18:25
  • 12
    The `..1` is unnecessary. – Keith Thompson Jul 19 '13 at 18:33
  • at least it looks to me that he is executing a shell script on a bash shell. – Pradheep Jul 19 '13 at 18:33
  • Adding the shebang did the trick. The c-like syntax still doesn't work, though. – sodiumnitrate Jul 21 '13 at 21:52
  • 6
    "..1" doesn't parse in MacOSX Bash. – Rondo Jul 25 '16 at 00:38
  • 3
    This does not work for me.~/u/tmp> cat try #!/bin/bash # for integer in {1..10..1} do echo "integer is $integer" done ~/u/tmp> ./try integer is {1..10..1} ~/u/tmp> – Jacob Wegelin Aug 30 '16 at 18:12
  • 10
    "..1" step size was added in bash 4.0+ – JGurtz Mar 03 '17 at 00:43
  • 1
    This answer ranges from 0-10. The loop in the question ranges from 1-10. My guess is that the questioner was accidentally running sh, not bash - his loop was perfect otherwise. – Adam Wildavsky Jun 30 '20 at 15:56
  • 3
    Note this does *not* work when using variables inside `{start..end..step}`, e.g. `{0..$end..1}`. With bash 5.0.17 `end=10; for i in {0..$end..1}; do echo $i; done` yields the output `{0..10..1}`. – balu Apr 16 '21 at 13:59
  • 2
    @balu Note that the question was not about using variables, so the answer is viable. If you need variables, then you can instead use the C-style version: `for (( $i = $start; $i <= $end; $i += $incr )) ...`. That works. – Alexis Wilke Nov 25 '21 at 21:20
  • @AlexisWilke I wasn't criticizing your answer, I just thought I'd leave a note for anyone else who'd try to use variables like I did. – balu Nov 27 '21 at 19:56
  • I like how `for i in {01..10}` will give you padded numbers ... `01` ... `02` .... – Stewart Nov 27 '22 at 21:23