3

I'm trying to write a bash script that's supposed to perform reverse DNS lookup on a range of IP addresses. The idea is to provide the network (first 3 octets) as $1, the start of the range to be checked as $2 and the end of said range as $3.

So I ended up with:

#!/bin/bash
if [ $# -ne 3 ]
then
    echo "[*] Usage: reverselookup.sh [Network (x.x.x)] [start of range (y)]  [end of range (z)]"
    exit 1
fi

for ip in {$2..$3}
do
    host $1.$ip | grep pointer
done

Now I thought that this would use the normal sequence operation in bash for loops, like in

for i in {2..5}

gives you a loop with 2, 3, 4 and 5. However it doesn't work.

If I echo the $ip inside the loop and run it as e.g.

reverselookup.sh 192.168.10 21 50

it presents me with

{21..50}

Does anyone know whether it's possible to make this work? Or do I have to rethink my appraoch?

Thanks in advance.

1
  • See the description of Brace Expansion to see why what you type won't work. Commented Sep 24, 2013 at 7:27

3 Answers 3

6

You can use seq to replace

for ip in {$2..$3}

Say:

for ip in $(seq $2 $3)
Sign up to request clarification or add additional context in comments.

2 Comments

The seq command is probably more portable that the c-style loop. The downside is that it will create an extra process, and that the number of iterations are limited by the size of the command buffer.
Thanks for the info as well as your approach but since the use case here is a maximum of 255 iterations this shouldn't be an issue. Please do correct me if that's wrong.
4

Brace expansion won't work with variables, because it is performed before the variable expansion. You can use a c-style for loop instead:

for ((ip=$2; ip<=$3; ip++))
do
    ....
done

Comments

3

You can use the seq command (part of coreutils) to generate the list; like so

for ip in $(seq $2 $3)
do
    host $1.$ip | grep pointer
done

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.