37

If I want to display the IP address that is assigned to eth1, how can I do this in Bash?

red0ct
  • 434
user47556
  • 589

14 Answers14

34

As @Manuel mentioned, ifconfig is out of date, and ip is the recommended approach going forward.

ip -f inet addr show eth1

and to use @bleater's sed or @Jason H.'s awk to filter the output (depending on if you want the mask)

ip -f inet addr show eth1 | sed -En -e 's/.*inet ([0-9.]+).*/\1/p'

ip -f inet addr show eth1 | awk '/inet / {print $2}'

ip -br addr show dev eth1 |awk '{print $3}'

Bill Weiss
  • 11,266
pstanton
  • 753
20

On a Linux system:

hostname --all-ip-addresses

will give you only the IP address.

On a Solaris system use:

ifconfig e1000g0 | awk '/inet / {print $2}'
Jason H.
  • 309
19

Try this (Linux)

/sbin/ifconfig eth1 | grep 'inet addr:' | cut -d: -f2| cut -d' ' -f1

or this (Linux)

/sbin/ifconfig eth0 | awk -F ' *|:' '/inet addr/{print $4}'

or this (*BSD)

ifconfig bge0 | grep 'inet' | cut -d' ' -f2

or this (Solaris 10)

ifconfig e1000g0 | awk '/inet / {print $6}'

Obviously change the interface name to match the one you want to get the information from.

user9517
  • 117,122
11

To obtain both IPv4 and IPv6 IP addresses with netmasks just try:

ip a l eth1 | awk '/inet/ {print $2}'

Or without netmasks (can't imagine why you need an IP address without a mask):

ip a l eth1 | awk '/inet/ {print $2}' | cut -d/ -f1
red0ct
  • 434
9

A better way: get ip adress from command "ip", because "ifconfig" is out of date. Otherwise you will get a problem on using "ifconfig", because the output of ifconfig is language dependend.

I use this command to get all IPs (IPv4):

ip addr show | grep -o "inet [0-9]*\.[0-9]*\.[0-9]*\.[0-9]*" | grep -o "[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*"
Manuel
  • 99
6

Works well on various linux:

ip -brief address show eth0 | awk '{print $3}' | awk -F/ '{print $1}'
tbo47
  • 161
3

on Ubuntu 20.04

$ sudo apt install moreutils
$ ifdata -pa eth0
192.168.1.152

3r1d
  • 131
  • 1
3

On recent OS and tools versions, using JSON interface should work too, e.g.:

 ip -json addr show docker0 \
 | jq '.[].addr_info[] | select(.family == "inet").local'

Which yields on my machine:

 "172.17.0.1"
2

maybe this will help

ifconfig eth1
1

ip addr show dev eth0 if you want to see all addresses for one interface

bryvo01
  • 11
  • 2
0

This is what I use:

ip r s | awk '/eth0/ {print $7}'

will print, for example: 192.168.0.1

lepe
  • 469
  • 2
  • 8
  • 25
0

On MacOS I use ipconfig getifaddr <interface-name>
The command is listed under the BSD System Manager's Manual.

0

One liner with sed:

ifconfig wlan0 | sed -En -e 's/.*inet ([0-9.]+).*/\1/p'

Replace wlan0 with the desired interface.

bleater
  • 121
0

I tried the accepted answer on CentOS 7, but it does not work.

/sbin/ifconfig eth0 | grep 'inet ' | tr -s ' ' | cut -d" " -f3

worked for me, in case someone else is also running into the same problem.

Michael Hampton
  • 252,907