This little script works for me -
[tt]
#!/bin/bash
/sbin/ifconfig | (grep 'inet addr:.*P\-t\-P' || echo '127.0.0.1') | awk '{sub(/inet addr:/, "" printf("%s\n", $1)}'
[/tt]
'ifconfig eth0' will give you only eth0 (the first ethernet device) information.
Next examine the output
inet addr: is your IP address. Bcast: Broadcast and Mask: is your netmask
The above script from ppc386 is more complicated than you need.
This will work
ifconfig eth0 | grep inet | awk '{print $2}'
Exchange eth0 for each device you want or just leave off eth0 to see all devices.
If you want to just see the ip and not see addr:x.x.x.x then add | awk -F ":" '{print $2}' to the command earlier. This will split addr:x.x.x.x into 2 seperate fields split on the :. $1 everything before the : and $2 everything after the colon.
> The above script from ppc386 is more complicated than you need.
I guess that depends on what you need.
The reason I put "#!/bin/bash" at the beginning of my scripts
is so the "file" command will tell me it is a script.
So if I do:
% file ~/bin/my-ip
I get:
~/bin/my-ip: Bourne-Again shell script text
instead of:
~/bin/my-ip: ASCII English text
That way, I can do something like:
file ~/bin/* | grep Bourne
- to get a list of all the scripts in a directory.
Since /sbin/ is only in the path for root on my machine,
I have to specify /sbin/ifconfig to run the script as
a normal user.
I connect to the net with a dial-up connection, so if the
connection is down, doing "ifconfig ppp0" gives me nothing
but an ugly error message:
ppp0: error fetching interface information: Device not found
That's not what I want, I would rather get the loopback IP if
ppp0 is down ( that's what the "|| echo 127.0.0.1" is about )
As far as chopping the "inet addr:" from the string...
I really don't see how my:
awk '{sub(/inet addr:/, "" printf("%s\n", $1)}'
is any more complicated than your:
awk '{print $2}' | awk -F ":" '{print $2}'
Why use two awks when one will do?
I like your idea of specifying the interface though,
( it cleans up the grep expression )
So I changed my script a little -
[tt]
/sbin/ifconfig ppp0 2> /dev/null | (grep inet || echo 127.0.0.1) | awk '{sub(/inet addr:/, "" printf("%s\n", $1)}'
[/tt]
That's the beautiful thing about open source, we all learn
from each other. To be honest, I didn't even know you could
specify an interface to ifconfig. So I learned something here
as well.
I tried reading through the awk maual, and picked up a couple
of tricks just before smoke started coming out my ears. [tt]*-@v@-*[/tt]
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.