You can use ifconfig eth0 | grep 'inet addr:'| grep -v '127.0. 0.1' | cut -d: -f2 | awk '{ print $1}' to get IP address of a specific interface, for instance in this example, eth0 .
Instead, you could just use this: hostname --all-ip-addresses or hostname -I , which does the same thing (gives you ALL IP addresses of the host).
There are no Booleans in Bash Bash does have Boolean expressions in terms of comparison and conditions. That said, what you can declare and compare in Bash are strings and numbers. That's it. Wherever you see true or false in Bash, it's either a string or a command/builtin which is only used for its exit code.
I've been struggling with this too until I've found there's a simple command for that purpose
hostname -i
Is that simple!
man hostname
recommends using the --all-ip-addresses
flag (shorthand -I
), instead of -i
, because -i
works only if the host name can be resolved. So here it is:
hostname -I
And if you are interested only in the primary one, cut
it:
hostname -I | cut -f1 -d' '
ip
is the right tool to use as ifconfig
has been deprecated for some time now. Here's an awk/sed/grep-free command that's significantly faster than any of the others posted here!:
ip=$(ip -f inet -o addr show eth0|cut -d\ -f 7 | cut -d/ -f 1)
(yes that is an escaped space after the first -d
)
You can take a look at this site for alternatives.
One way would be:
ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}'
A bit smaller one, although it is not at all robust, and can return the wrong value depending on your system:
$ /sbin/ifconfig | sed -n '2 p' | awk '{print $3}'
(from http://www.htmlstaff.org/ver.php?id=22346)
The ifdata command (found in the moreutils package) provides an interface to easily retrieve ifconfig data without needing to parse the output from ifconfig manually. It's achieved with a single command:
ifdata -pa eth1
Where eth1
is the name of your network interface.
I don't know how this package behaves when ifconfig is not installed. As Syncrho stated in his answer, ifconfig has been deprecated for sometime, and is no longer found on a lot of modern distributions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With