K.U
K.U

Reputation: 303

Generating a list of IP addresses in a Bash loop

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

Upvotes: 13

Views: 43690

Answers (1)

Benjamin W.
Benjamin W.

Reputation: 52132

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!

Upvotes: 32

Related Questions