Run through two sequences in one loop

I'm trying to run through two sequences in the same loop in my shell like below:

#!/bin/bash
for i in (1..15) and (20..25) ;
do
     echo $i
     ......
     .....other process
done

any idea how I can achieve this?


Solution 1:

You only need brace expansion for that

$ for n in {1..3} {200..203}; do echo $n; done
1
2
3
200
201
202
203

We can pass a list to for (for i in x y z; do stuff "$i"; done).

So here, braces { } get the shell to expand your sequences into a list. You only need put a space between them, since the shell splits lists of arguments on those.

Solution 2:

Alternatively we can use seq (print a sequence of numbers), here are two equivalent examples:

for i in `seq 1 3` `seq 101 103`; do echo $i; done
for i in $(seq 1 3) $(seq 101 103); do echo $i; done

If it is a script, for repetitive tasks, you can use functions:

#!/bin/bash
my_function() { echo "$1"; }
for i in {1..3}; do my_function "$i"; done
for i in {101..103}; do my_function "$i"; done
#!/bin/bash
my_function() { for i in `seq $1 $2`; do echo "$i"; done; }
my_function "1" "3"
my_function "101" "103"