Get ip adress from ifconfig output

Sometimes you might need your machines IP adress in a script. There are solutions to this using external sources, but that wont always work 😉 So heres how to get your IP from your computers data.. (Using grep)

You sometimes need your machines IP adress without relying on external sources; so here is the command to return your IP adress in one neat line.

ifconfig eth0 | grep -o "addr:[0-9.]*" | grep -o "[0-9.]*"

You off course need the necessary rights to us this. If you lack the rights, you might want to prepend it with “sudo” and add the ifconfig to the allowed paswordless commands for the user that needs this..

Ifconfig retrieves the adress; the first grep weeds out the external adress out of the data & the last grep filters out the IP adress.

I posted this to shell-fu and will link it here should it be published..

Edit: Shell-Fu published it today – hooray for being usefull 🙂 Shell-Fu: 554

Published by Gert

Person-at-large.

3 thoughts on “Get ip adress from ifconfig output

  1. $ ifconfig eth0 | awk ‘/inet addr/ {split ($2,A,”:”); print A[2]}’

    $ ifconfig eth0 | grep -o “addr:[0-9.]*” | cut -b6-

    $ hostname -i

    cheers,
    paul

    Like

  2. If you’re using Linux, why not just use ip addr ls dev foo? Note that your solution will yield “interesting” results on a system with multiple addresses. It also fails to take into account IPv6 addresses.

    Like

  3. Grep can indeed be replaced with a bunch of other commands 🙂 But the greps work, so I’ll keep them. As for the hostname & ip commands, those dont give me quite the expected results..

    The script does indeed not take the IPv6 nor multiple adresses into account, but since thats not the case where I’m using it, that doesnt really matter to me 😉 (And adjusting the script to do so wouldnt be that hard either)

    Thanks for the feedback 🙂

    Like

Leave a comment