How to produce range with step n in bash? (generate a sequence of numbers in increments)

The way to iterate over a range in bash is

for i in {0..10}; do echo $i; done 

What would be the syntax for iterating over a sequence with a step? Say I would like to get only an even number in the above example.

+81
bash range
Jun 08 '09 at 17:31
source share
4 answers

I would do

 for i in `seq 0 2 10`; do echo $i; done 

(although, of course, seq 0 2 10 itself will produce the same result).

Note that seq allows for a floating point number (for example, seq .5 .25 3.5 ), but the bash extension extensions allow only integers.

+126
Jun 08 '09 at 17:35
source share

Bash 4 The brace extension has a step function:

 for {0..10..2}; do .. done 

Regardless of whether Bash 2/3 (C-style for the loop, see answers above) or Bash 4, I would prefer something on the seq command.

+66
Jun 08 '09 at 17:58
source share

Clean Bash, without additional process:

 for (( COUNTER=0; COUNTER<=10; COUNTER+=2 )); do echo $COUNTER done 
+42
Jun 08 '09 at 17:48
source share
 #!/bin/bash for i in $(seq 1 2 10) do echo "skip by 2 value $i" done 
+11
Jun 08 '09 at 17:35
source share



All Articles