Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested Bash while loop, inner loop is only loop looping

This is a very simple script but I can't seem to get it right. This code is supposed to print out class C IP addresses from 192.168.0.0 - 192.168.255.255 but all that prints out is 192.168.0.0 - 192.168.0.255. For some reason my outer loop won't loop. I'm sure it is something stupid but this could be helpful for those people learning nested looping in shell scripts. Any other advice is welcome!

#! /bin/sh
network_id="192.168."
count1=-1
count2=-1
while [ "$count1" -le 254 ]
do
    count1=$(($count1+1))
    while [ "$count2" -le 254 ]
    do
        count2=$(($count2+1))
        printf "%s%s%s%s\n" $network_id $count1 "." $count2
    done
done
exit 0
like image 935
Colin93 Avatar asked Jan 06 '23 17:01

Colin93


2 Answers

You are not resetting count2. Your outer loop is running 256 times, but the inner loop stops after running through once.

If you add count2=-1 after closing inner loop, it will work as expected.

For clarity, I would move your increment so you are clearly iterating between 0-255. Here's how I'd write it:

#! /bin/sh
network_id="192.168."
count1=0
count2=0
while [ "$count1" -le 255 ]; do
    while [ "$count2" -le 255 ]; do
        printf "%s%s%s%s\n" $network_id $count1 "." $count2
        count2=$(($count2+1))
    done
    count2=0
    count1=$(($count1+1))
done
like image 109
uint128_t Avatar answered Jan 14 '23 12:01

uint128_t


Nothing but a small mistake. You didnot set $count=-1

#! /bin/sh
network_id="192.168."
count1=-1
count2=-1
while [ "$count1" -le 254 ]
do
    count1=$(($count1+1))
    while [ "$count2" -le 254 ]
    do
        count2=$(($count2+1))
        printf "%s%s%s%s\n" $network_id $count1 "." $count2
    done
    count2=-1
done
exit 0

This should work.

like image 35
sudheesh shetty Avatar answered Jan 14 '23 13:01

sudheesh shetty