I need a list of IP addresses from 130.15.0.0 to 130.15.255.255. I tried this but I realized it will create 255 lists. Can anyone please help me figure this out?
for (( i = 0; i <= 255; i++)) ; do
for (( j = 0; j <= 255; j++)) ; do
LIST="$LIST 130.15.$i.$j"
done
done
We can iterate over the array elements using the @ operator that gets all the elements in the array. Thus using the for loop we iterate over them one by one. We use the variable ${variable_name[@]} in which, the curly braces here expand the value of the variable “s” here which is an array of strings.
I'd say that your approach works, but it is very slow1. You can use brace expansion instead:
echo 135.15.{0..255}.{0..255}
Or, if you want the result in a variable, just assign:
list=$(echo 135.15.{0..255}.{0..255})
If you want the addresses in an array, you can skip the echo
and command substitution:
list=(135.15.{0..255}.{0..255})
Now, list
is a proper array:
$ echo "${list[0]}" # First element
135.15.0.0
$ echo "${list[@]:1000:3}" # Three elements in the middle
135.15.3.232 135.15.3.233 135.15.3.234
Comments on your code:
Instead of
list="$list new_element"
it is easier to append to a string with
list+=" new_element"
If you wanted to append to an array in a loop, you'd use
list+=("new_element")
1 In fact, on my machine, it takes almost six minutes – the brace expansion takes less than 0.1 seconds!
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