How to iterate over multiple discontinuous ranges in a bash for loop

Note: I am NOT asking this question

I was looking for information on how to iterate over a series of underdeveloped numbers, such as 0,1,2,4,5,6,7,9,11, without having to enter numbers manually and use ranges.

An obvious way would be to do this:

for i in 0 1 2 4 5 6 7 9 11; do echo $i; done 
+6
source share
4 answers
 for i in {0..2} {4..6} {7..11..2}; do echo $i; done 

See the bash bracket extension documentation .

+15
source

Edit: oops, did not understand that the numbers were missing.

Update: Define ranges, and then use a while loop for each range. eg.

 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

+2
source

As others have noted, brace expansion provides a way to select ranges, but you can also assign the results of multiple braces to a variable using echo {..} {..} . This can lead to typing in the for loop tag:

 #!/bin/bash range="`echo {2..6} {31..35} {50..100..10}`" for i in $range; do echo $i; done exit 0 

output:

 2 3 4 5 6 31 32 33 34 35 50 60 70 80 90 100 
+2
source
 for i in `cat file.txt`; do echo $i; done 

where file.txt contains:

 0 1 2 4 5 6 7 9 11 
+1
source

Source: https://habr.com/ru/post/973520/


All Articles