Pure bash method to get the IP from eth0

I needed a pure bash way to get just the raw IP address from eth0

# Get the IP address line of eth0 from ifconfig 
line=$(ifconfig eth0 | head -n2 | tail -n1)

# Regexp to match just the IP part
reg="addr:([0-9\.]+)\s" 

# Run the regexp and print out the match
[[ $line =~ $reg ]]
echo ${BASH_REMATCH[1]}

Or the same thing on one line

line=$(ifconfig eth0 | head -n2 | tail -n1);reg="addr:([0-9\.]+)\s";[[ $line =~ $reg ]]; echo ${BASH_REMATCH[1]}

Or here is another way to do it using cut

# Cut on the spaces and find the 12th field (addr:1.2.3.4) then get the string starting at the 6th char
ifconfig eth0 | head -n2 | tail -n1 | cut -d' ' -f12 | cut -c 6-
Leave A Reply - 1 Reply
Replies
Greg 2012-12-08 01:10am - No Email - Logged IP: 50.89.47.246

ifconfig eth0 | ( while read line; do [ "$line" != "${line#inet }" ] && e="${line#inet }" && e="${e%%[ ]}" && e="${e##[A-Za-z:]}" && echo "$e" ; done )

All content licensed under the Creative Commons License