LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Server (http://www.linuxquestions.org/questions/linux-server-73/)
-   -   A question about for loop (increasing two parameters) (http://www.linuxquestions.org/questions/linux-server-73/a-question-about-for-loop-increasing-two-parameters-920733/)

yaron.kadem 12-27-2011 10:33 AM

A question about for loop (increasing two parameters)
 
Hi All,

I have a question about the for loop in Bash, I would like to produce plenty of lines using for loop where the first field increases by one but only when the second one reaches its limit.

I would like the third octet of the IP address 1.1.1.1 to change to the number 2 but only when the fourth octet reaches the number 5.

for i in {1..5};do echo "ip route add 1.1.1.$i/32 via 192.168.168.1";done

here is an example of what I need my for loop to do:

ip route add 1.1.1.1/32 via 192.168.168.1
ip route add 1.1.1.2/32 via 192.168.168.1
ip route add 1.1.1.3/32 via 192.168.168.1
ip route add 1.1.1.4/32 via 192.168.168.1
ip route add 1.1.1.5/32 via 192.168.168.1
ip route add 1.1.2.1/32 via 192.168.168.1
ip route add 1.1.2.2/32 via 192.168.168.1
ip route add 1.1.2.3/32 via 192.168.168.1
ip route add 1.1.2.4/32 via 192.168.168.1
ip route add 1.1.2.5/32 via 192.168.168.1


Help would be much appreciated.

Yaron

T3RM1NVT0R 12-27-2011 10:51 AM

@ Reply
 
Hi yaron.kadem,

You have to use 2 loops to achieve the required output. It will look like as follows:
Code:

#!/bin/bash
for j in {1..5}
do
    for i in {1..5}
    do
            echo "ip route add 1.1.$j.$i/32 via 192.168.168.1"
            if [ $i = 5]
            then
                  continue
            fi
    done
done

[code]

yaron.kadem 12-27-2011 11:04 AM

@ reply
 
Wow, thanks a lot, it works perfectly.


thanks

T3RM1NVT0R 12-27-2011 11:07 AM

@ Reply
 
You're welcome. Enjoy linux!!!

Please mark this thread as solved.

David the H. 12-27-2011 01:42 PM

Or you can use a single brace expansion expression to do the whole thing:

Code:

printf "%s\n" "ip route add 1.1."{1..5}.{1..5}"/32 via 192.168.168.1"
brace expansion :cool:

yaron.kadem 12-28-2011 02:25 AM

@ reply
 
thanks David for another way to do that.

Yaron


All times are GMT -5. The time now is 02:06 AM.