For scanning my subnet using my IP address, I need to run the following command

nmap -sn 192.168.100.*

I want to extend this functionality such that I don't have to manually specify the first three parts of the IP range myself. I came up with this rough solution.

ip=$( hostname -I | awk '{print $1}' | awk -F. '{print $1; print $2; print $3}' ORS="."; echo -n "*"); 
nmap -sn $ip

Is there a more cleaner way of achieving the same?


2 Answers 2


This is pretty reasonable. I'd have awk do a bit more of the work:

ip=$( hostname -I | awk '{print $1}' | awk -F. '{OFS="."; print $1, $2, $3,"*"}'; );

I switched from ORS (output record separator) to OFS (output field separator) to use print in awk with commas. The commas tell it that we have multiple fields which gets rid of two "extra" print statements. This also let me move the literal * inside of awk which eliminates the shell echo. So I feel this is more succinct without being harder to follow.

It might be nice to combine the awks into one, but it is pretty clear what each one does and it isn't like you're processing reams of data here.

  • 2
    \$\begingroup\$ You could drop awk '{print $1}' in the middle and expect the same output ;-) \$\endgroup\$
    – janos
    Nov 30, 2018 at 17:22

You can do it purely in Bash, using ${parameter%word} to strip off the last octet from the IP address.

hostname -I | while read ip _ ; do
    nmap -sn  ${ip%.*}.\*

Note that hostname -I is not portable: the -I option appears to be a GNU extension.

  • 3
    \$\begingroup\$ Although it's reasonable to expect that hostname -I will not output something malicious, as a rule of thumb it's always good to double-quote variables used in command arguments, and written like this might be slightly kinder on the eyes too: nmap -sn "${ip%.*}.*" \$\endgroup\$
    – janos
    Nov 30, 2018 at 17:27

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.