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

BashRangeIteration

Bash Problem Overview


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 the sequence with a step? Say, I would like to get only even number in the above example.

Bash Solutions


Solution 1 - Bash

I'd do

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

(though of course seq 0 2 10 will produce the same output on its own).

Note that seq allows floating-point numbers (e.g., seq .5 .25 3.5) but bash's brace expansion only allows integers.

Solution 2 - Bash

Bash 4's brace expansion has a step feature:

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

No matter if Bash 2/3 (C-style for loop, see answers above) or Bash 4, I would prefer anything over the 'seq' command.

Solution 3 - Bash

Pure Bash, without an extra process:

for (( COUNTER=0; COUNTER<=10; COUNTER+=2 )); do
	echo $COUNTER
done

Solution 4 - Bash

#!/bin/bash
for i in $(seq 1 2 10)
do
   echo "skip by 2 value $i"
done

Solution 5 - Bash

Use seq command:

$ seq 4
1
2
3
4

$ seq 2 5
2
3
4
5

$ seq 4 2 12
4
6
8
10
12

$ seq -w 4 2 12
04
06
08
10
12

$ seq -s, 4
1,2,3,4

Solution 6 - Bash

brace expansion {m..n..s} is more efficient than seq. AND it allows a bit of output formatting:

$ echo {0000..0010..2}
0000 0002 0004 0006 0008 0010

which is useful if one numbers e.g. files and want's a sorted output of 'ls'.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSilentGhostView Question on Stackoverflow
Solution 1 - BashchaosView Answer on Stackoverflow
Solution 2 - BashTheBonsaiView Answer on Stackoverflow
Solution 3 - BashFritz G. MehnerView Answer on Stackoverflow
Solution 4 - Bashz -View Answer on Stackoverflow
Solution 5 - BashMir-IsmailiView Answer on Stackoverflow
Solution 6 - BashMichael_MaierView Answer on Stackoverflow