Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a list of IP addresses in a Bash loop

Tags:

bash

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
like image 587
K.U Avatar asked Oct 29 '16 23:10

K.U


People also ask

How do you iterate through a bash script?

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.


1 Answers

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")
    
  • Uppercase variable names are not recommended as they're more likely to clash with environment variables (see POSIX spec, paragraph four)

1 In fact, on my machine, it takes almost six minutes – the brace expansion takes less than 0.1 seconds!

like image 74
Benjamin W. Avatar answered Oct 22 '22 23:10

Benjamin W.