Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I iterate over multiple, discontinuous ranges in a bash for loop

Tags:

bash

Note: I am NOT asking this question

I looked for information on how to loop over a range of discontiguous numbers such as 0,1,2,4,5,6,7,9,11 without having to put the numbers in by hand and still use the ranges.

The obvious way would be to do this:

for i in 0 1 2 4 5 6 7 9 11; do echo $i; done
like image 557
MrMas Avatar asked Aug 08 '14 01:08

MrMas


2 Answers

for i in {0..2} {4..6} {7..11..2}; do echo $i; done

See the documentation of bash Brace Expansion.

like image 51
Barmar Avatar answered Oct 12 '22 11:10

Barmar


Edit: oops, didn't realise there were missing numbers.

Updated: Define ranges and then use a while loop for each range. e.g.

ranges="0-2 4-7 9 11"
for range in $ranges
do
    min=${range%-*}
    max=${range#*-}
    i=$min
    while [ $i -le $max ]
    do
        echo $i
        i=$(( $i + 1 ))
    done
done

http://ideone.com/T80tfB

like image 36
Sodved Avatar answered Oct 12 '22 09:10

Sodved