79

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.

4
  • Your code works fine for me in 4.1.5 Commented Jul 19, 2013 at 18:23
  • 1
    You can also print a range of numbers using seq. Try "seq 1 5". Commented Jul 19, 2013 at 18:27
  • 7
    If you execute bash as sh, it won't work; if you execute bash as bash, it will work. Commented Jul 19, 2013 at 18:27
  • C-syntax works when you do let i= 0 before the for loop condition. Commented May 11, 2019 at 3:46

1 Answer 1

129

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/.

Sign up to request clarification or add additional context in comments.

13 Comments

This: (note the shebang says bash, not sh)
The ..1 is unnecessary.
"..1" doesn't parse in MacOSX Bash.
"..1" step size was added in bash 4.0+
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}.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.