Linux: Parse an IP Address

How do I parse my Linux servers IP address using a Bash shell?

You need to use the ifconfig or ip command to get ip address under Linux.

Parse an IP Address with ifconfig Command

Open a command-line terminal (select Applications > Accessories > Terminal), and then type the following commands:
# ifconfig eth0 | grep 'inet addr:'
Sample outputs:

          inet addr:  Bcast:  Mask:

To get only an IP address, Bcast and Mask, use the egrep command as follows:
# ifconfig eth0 | egrep '([0-9]{1,3}\.){3}[0-9]{1,3}'
Sample outputs:

Parse an IP Address with ip Command

Use the ip command as follows:
# ip -f inet addr show eth0| grep 'inet'
Sample outputs:

inet brd scope global eth0

Just display an IP:
# ip -f inet addr show eth0 | awk -F'inet' '{ print $2}' | cut -d' ' -f21

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 2 comments so far... add one

CategoryList of Unix and Linux commands
Disk space analyzersdf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
2 comments… add one
  • Scooter Nov 30, 2015 @ 20:58

    On Ubuntu 14.04 LTS, your ‘ip addr’ example (ip -f inet addr show eth0 | awk -F’inet’ ‘{ print $2}’ | cut -d’ ‘ -f21) outputs nothing.

    First wanted to comment, parsing output of a command would generally be considered to not be “production quality code”. This applies to my working example also :-)

    ip -f inet addr show eth0 | awk '/inet /{ print $2}'|cut -d'/' -f1

    In general, be VERY careful about using -f with whitespace… different OS distros may handle this differently (are 4 spaces considered one block of whitespace? Or 4? What about a single tab?). awk is better about supporting different “whitespace” scenarios, than simple ‘cut’ is.

    Anyone could clean up my code further (or point out edge cases where it fails, as I would if your iface IP address weren’t a typical /24)

  • Sridhar Chandrasekaran Apr 20, 2017 @ 4:57

    ifconfig | awk -F “:” ‘/inet addr/{split($2,a,” “);print a[1]}’ | awk ‘NR==1{print $1}’

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum