How to produce a range with step n in bash? (gener

2019-01-30 17:04发布

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.

4条回答
我命由我不由天
2楼-- · 2019-01-30 17:20

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.

查看更多
Animai°情兽
3楼-- · 2019-01-30 17:27

Pure Bash, without an extra process:

for (( COUNTER=0; COUNTER<=10; COUNTER+=2 )); do
    echo $COUNTER
done
查看更多
我只想做你的唯一
4楼-- · 2019-01-30 17:28
#!/bin/bash
for i in $(seq 1 2 10)
do
   echo "skip by 2 value $i"
done
查看更多
来,给爷笑一个
5楼-- · 2019-01-30 17:40

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.

查看更多
登录 后发表回答