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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With