tags:

views:

848

answers:

4

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.

+1  A: 

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

chaos
Dear downvoter: I had exactly 15000 rep, and now I have 14998. I will never forgive you.
chaos
+2  A: 
#!/bin/bash
for i in $(seq 1 2 10)
do
   echo "skip by 2 value $i"
done
yx
+8  A: 

Pure Bash, without an extra process:

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

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.

TheBonsai
could you explain why?
SilentGhost
and btw, do you know if bash4 is default on any major OS?
SilentGhost
Bash4 still isn't mainstream, no. Why not seq? Well, let's say it with the words of the bot in the IRC channel #bash: "seq(1) is a highly nonstandard external command used to count to 10 in silly Linux howtos."
TheBonsai
my understanding is that seq is a part of coreutils. what is non-standard about it? arguments? thanks for your help.
SilentGhost
These arguments may or may not count for you: * there are enough systems without GNU coreutils (but Bash installed) * you create an unneeded external process * you rely on the idea that all 'seq' do what your 'seq' does * it's not standardized by the ISO
TheBonsai