Tech Tip: Getting Your MAC and IP Address In a Script


Ever wanted to get the MAC or IP address of your computer in a Linux shell script? The following two commands should work on most flavours of Linux/Unix.

To get your IP address:

/sbin/ifconfig \
   | grep '\<inet\>' \
   | sed -n '1p' \
   | tr -s ' ' \
   | cut -d ' ' -f3 \
   | cut -d ':' -f2

To get your MAC address (Hardware address):

/sbin/ifconfig \
   | grep 'eth0' \
   | tr -s ' ' \
   | cut -d ' ' -f5

Note that this retrieves the address of the eth0 interface by default.



Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

How about this: hostname -i

Anonymous's picture

How about this:

hostname -i

this one-liner shows all IP addresses for all interfaces

freephile's picture

/sbin/ifconfig | grep 'inet addr:'| grep -v '' | cut -d: -f2 | sort | awk '{print "# "$1}'

get your IP

kaloyan's picture

ifconfig eth0
| sed -n '/inet addr:/p'
| cut -d: -f2
| cut -d" " -f1

all in one

Anonymous's picture

ifconfig ath0 | perl -ne 'm/.*HWaddr (\S+).*/ && print "$1 ";m/.*inet addr:(\S+)/ && print "$1\n"'

Perl could be used for extracting both IPv4 and IPv6:

Roland Müller's picture
# ifconfig | perl -ne '(s|^\s+inet6\s+addr:\s*([0-9a-f:/]+)\s+.*|${1}| or s|^\s+inet\s+addr:\s*([0-9.]+)\s+.*|${1}|) and print;'

showing mac address

Joe Eykholt's picture

To show MAC:

cat /sys/class/net/eth0/address


Kwirkie's picture

How about...

ifconfig eth1 | egrep -o '([0-9]{1,3}\.){3}[0-9]{1,3}' | sed -n '1p'

ifconfig eth1 | egrep -o '([[:xdigit:]]{2}[:]){5}[[:xdigit:]]{2}'

This provides validation and also the regexp can be used elsewhere to find IPs and MACs

IP: ip addr show dev eth0 |

zsteva's picture

ip addr show dev eth0 | sed -e's/^.*inet \([^ ]*\)\/.*$/\1/;t;d'

ip addr show dev eth0 | sed -e's/^.*link[^ ]* \([^ ]*\) .*$/\1/;t;d'

or with /sbin/ifconfig

/sbin/ifconfig wlan0 | sed -e's/^.*inet addr:\([^ ]*\) .*$/\1/;t;d'

/sbin/ifconfig eth0 | sed -e's/^.*HWaddr \([^ ]*\) .*$/\1/;t;d'