Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm attempting to write an automated script which will update the IP address for my Raspberry Pi within my /etc/hosts file.

I'm able to execute this line just fine,

IP=`sudo nmap -sP 10.61.4.0/24 | awk '/^Nmap/{ip=$NF}/B8:27:EB/{print ip}'`

But I want to make the script more modular by being able to easily modify the IP address subnet and/or MAC address with the use of variables. Therefore, I made variables MY_MAC and MY_LOCAL_IP_SUBNET which are equal to some terminal input that I must provide when running the script.

I wanted to be able to do something like,

IP=`sudo nmap -sP $MY_LOCAL_IP_SUBNET | awk '/^Nmap/{ip=$NF}/$MY_MAC/{print ip}'`

It runs, and I have gotten it to work the MY_LOCAL_IP_SUBNET variable, but it doesn't return a IP address when the MY_MAC variable is used. I've tried playing around with this as much as I could, but I cannot seem to get it to work. Any ideas?

share|improve this question
    
You can try IP=sudo nmap -sP ${MY_LOCAL_IP_SUBNET} | awk '/^Nmap/{ip=$NF}/$MY_MAC/{print ip}' – alpert Dec 10 '15 at 8:14
    
No ideias at at with you are trying to do, between the text and commands you intentions are not clear at all. From the commands, trying to locate the Pi in the network? Why not drinking from DHCP, or putting it sending a ping to you when it boots? – Rui F Ribeiro Dec 10 '15 at 8:14
    
Rui, I am writing a script within my Linux VM to automatically update the IP address for my Raspberry Pi within /etc/hosts so I can have a lazy and quick way to SSH. It's mostly also just to see if I can do it :) – user138741 Dec 11 '15 at 3:51
up vote 2 down vote accepted

You are using ' in awk '/^Nmap/{ip=$NF}/$MY_MAC/{print ip}'. ' doesn't expand shell variables so $MY_MAC in that case is literally the string $MY_MAC.

You can use double quotes to expand the variable

IP=$(sudo nmap -sP $MY_LOCAL_IP_SUBNET | awk "/^Nmap/{ip=$NF}/$MY_MAC/{print ip}")

but that will conflict with $NF from awk.

So use the -v flag to add an awk variable and use $0~mymac to match the current line against the pattern in mymac

IP=$(sudo nmap -sP $MY_LOCAL_IP_SUBNET | awk -v mymac="$MY_MAC" '/^Nmap/{ip=$NF}$0~mymac{print ip}')
share|improve this answer
    
Thanks! That did the trick perfectly! Everytime I attempt to reach into the world of awk I quickly get smacked in the face and get rejected from the club, maybe someday I'll get the grip of it :) – user138741 Dec 11 '15 at 6:04

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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