1

How can I pass an optional argument to a bash script that will replace an existing variable in the script? For example:

#!/bin/bash
#hostfinder.sh
#Find hosts in current /24 network

subnet=$(hostname -i | cut -d. -f1,2,3)

for j in \
    $(for i in $subnet.{1..255}; do host $i; done | grep -v not | cut -d" " -f5)
do ping -c1 -w 1 $j; done | grep -i from | cut -d" " -f3,4,5 | tr ':' ' ' | \
sed -e 's/from/Alive:/'

This will grab the IP of the current host, run a reverse lookup against possible neighbors, ping test any hostnames it finds, and display an output similar to this:

Alive: host1.domain (10.64.17.23)
Alive: host2.domain (10.64.17.24)
...

Call me crazy, but it's way faster than nmap and spits out a nice list.

Anyway, I'd like to optionally pass the first three octets of any class C network address to the $subnet variable as the $1 argument when executing the script. For example:

./hostfinder.sh 10.20.0

My first thought was to try something like $subnet=$1, but I assume that will not work. I'm not really interested in re-writing the script to be more elegant or anything, I am mostly just curious about what I put in the subject line.

4
  • nmap is meant to do a completely different thing. Commented Mar 13, 2013 at 9:41
  • nmap can do a lot of things, though. :) Commented Mar 13, 2013 at 9:47
  • Also, I think a ping sweep with nmap goes something like this: nmap -sP 192.168.1.1-254 Commented Mar 13, 2013 at 9:50
  • Did subnet=$1 not work for you? Commented Mar 13, 2013 at 10:22

3 Answers 3

2

How about replace:

subnet=$(hostname -i | cut -d. -f1,2,3)

with:

case $# in  
  0) subnet=$(hostname -i | cut -d. -f1,2,3);;
  1) subnet="${1}";;
  *) echo "To many arguments" >&2; exit 1;;
esac
  • $# is the number of command line arguments
  • This is less elegant as getopt but easy to understand and extend.
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I will play with this and respond.
That worked like a champ. Thanks a lot! I can extend it with more options for class A or B now. This will turn into a nice portable sweeper where I don't have nmap installed or when nmap -sP just doesn't seem to work on certain subnets with hosts I need to inventory.
0

Try using getopt, to read from the options in the command line, and then set your variable.

1 Comment

Thanks for the suggestion. Would you mind sharing a bit of an example, please?
-1

Like LtWorf suggested, try using getopt. Its read the options and its arguments from the command line.

You can find a great example of getopt usage here: getopt usage example

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.