I want to edit the bashrc file to have a simple function called \"myip\" to run. As you might guess, the function myip prints only my internal IP address of my machine.
Similar to JSR, but with awk
and cut
in reverse order:
my_ip=$(ifconfig en1 | grep 'inet addr' | awk '{print $2}' | cut -d: -f 2)
echo ${my_ip}
Both the following work here (CentOS 5).
ip addr show eth0 | awk '$1 == "inet" {gsub(/\/.*$/, "", $2); print $2}'
ifconfig eth0 | awk '/inet addr/ {gsub("addr:", "", $2); print $2}'
For OS X (v10.11 (El Capitan) at least):
ifconfig en0 | awk '$1 == "inet" {print $2}'
No need to do unportable ifconfig parsing in Bash. It's a trivial one-liner in Python:
python -c 'import socket; print(socket.gethostbyname(socket.gethostname()))'
Taking patch's answer, making it a bit more general,
i.e.: skipping everything till the first digit.
ifconfig eth0 | awk '/inet addr/{sub(/[^0-9]*/,""); print $1}'
Or even better:
ifconfig eth0 | awk '/inet /{sub(/[^0-9]*/,""); print $1}'
Using Perl Regex:
ifconfig eth0 | grep -oP '(?<= inet addr:)[^ ]+'
Explanation: grep -oP searches for an EXACT match using Perl regex.
The "tricky" part is the regex itself;
1. (?<= inet addr:)
means - that the string inet addr:
is to the LEFT of what we're looking for.
2. [^ ]+
(please notice the space after the ^ ) - it means to look for everything until the first blank - in our case it is the IP Address.
This code outputs IP addresses for all network connections (except loopback) and is portable between most OS X and Linux versions.
It's particularly useful for scripts that run on machines where:
The script is:
/sbin/ifconfig -a | awk '/(cast)/ {print $2}' | cut -d: -f2
This can be assigned to a variable in a script like this:
myip=$(/sbin/ifconfig -a | awk '/(cast)/ {print $2}' | cut -d: -f2)
Scripts can handle possible multiple addresses by using a loop to process the results, as so:
if [[ -n $myip ]]; then
count=0
for i in $myip; do
myips[count]=$i # Or process as desired
((++count))
done
numIPaddresses=$count # Optional parameter, if wanted
fi
Notes:
After trying some solutions i find this most handy, add this to your alias:
alias iconfig='ifconfig | awk '\''{if ( $1 >= "en" && $2 >= "flags" && $3 == "mtu") {print $1}; if ( $1 == "inet" || $1 == "status:"){print $0};}'\''|egrep "en|lo|inet"'
the output looks like this:
shady@Shadys-MacBook-Pro:xxxx/xxx ‹dev*›$ iconfig
lo0:
inet 127.0.0.1 netmask 0xff000000
en0:
inet 10.16.27.115 netmask 0xffffff00 broadcast 10.16.27.255
en1:
en2:
en5:
inet 192.168.2.196 netmask 0xffffff00 broadcast 192.168.2.255