Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash for loop: a range of numbers [duplicate]

Tags:

bash

for-loop

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.

like image 882
sodiumnitrate Avatar asked Jul 19 '13 18:07

sodiumnitrate


People also ask

How do I iterate over a range of numbers defined by variables in bash?

You can iterate the sequence of numbers in bash in two ways. One is by using the seq command, and another is by specifying the range in for loop. In the seq command, the sequence starts from one, the number increments by one in each step, and print each number in each line up to the upper limit by default.

What is $() in bash?

$( command ) or. ` command ` Bash performs the expansion by executing command in a subshell environment and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting.

What is $1 $2 in shell script?

$1, $2, $3 etc. represent the first, second, third, etc. arguments to the script. $# represents the number of arguments. $* represents the string of arguments.

How do you use seq in a for loop?

The seq command generates a number sequence. Parse the sequence in the Bash script for loop as a command to generate a list. The output prints each element generated by the seq command. The seq command is a historical command and not a recommended way to generate a sequence.


1 Answers

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

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

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

like image 67
Pradheep Avatar answered Oct 11 '22 10:10

Pradheep