Search code examples
shellgnome-terminal

Script to set IP address connected to an interface to a shell variable


I want to write a script to set the IP address of the device connected to an interface like "eth0" to a variable. I can get the IP address by this command:

arp -i eth0 -a

The output of above command is:

? (10.42.0.38) at b8:27:eb:07:5d:60 [ether] on eth0

I want to add a script to .bashrc file to set the IP address from output of above command to the variable $RASPBERRY_IP and use it in other script. Any idea how to do that?


Solution

  • Your ARP table is not the right source to find your local IP address. Try the ip command instead:

    RASPBERRY_IP=$(ip addr | awk -F"[ /]" '/inet .*eth0/{print $6}')
    

    If you want to find another IP address in your network, you can use your ARP table. Try this command:

    RASPBERRY_IP=$(arp -ai eth0 | cut -d' ' -f2 | sed 's/[()]//g')
    

    Note that $RASPBERRY_IP will contain more IP addresses if your ARP table contains more entries on eth0! Example: 10.42.0.38 10.42.0.39 10.42.0.40. Add a grep with the raspberry's MAC address. If you only want the first entry, change it to:

    RASPBERRY_IP=$(arp -ai eth0 | cut -d' ' -f2 | sed 's/[()]//g;q')
    

    Don't forget that ARP removes entries from the ARP cache after some time (usually 5 minutes under Unix).