Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you increment a variable in bash?

Increment Bash Variable with += Operator Another common operator which can be used to increment a bash variable is the += operator. This operator is a short form for the sum operator. The first operand and the result variable name are the same and assigned with a single statement.

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

What does N mean in bash?

-n is one of the string operators for evaluating the expressions in Bash. It tests the string next to it and evaluates it as "True" if string is non empty. Positional parameters are a series of special variables ( $0 , $1 through $9 ) that contain the contents of the command line argument to the program.


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.


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.


Pure Bash, without an extra process:

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

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