I a bash script, I want to obtain the global IPv6 address of my machine for a given network adapter (on my case 'ens18'). To get started, I issued the following command:
ip -6 addr
This gives me the followig output, which contains the address I'm looking for:
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 state UNKNOWN qlen 1000
inet6 ::1/128 scope host noprefixroute
valid_lft forever preferred_lft forever
2: ens18: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 state UP qlen 1000
inet6 fd00::3170:4ff:eff4:a4ab/64 scope global dynamic mngtmpaddr noprefixroute
valid_lft 6736sec preferred_lft 3136sec
inet6 2a02:8070:2982:4300:3170:4ff:eff4:a4ab/64 scope global dynamic mngtmpaddr noprefixroute
valid_lft 6736sec preferred_lft 3136sec
inet6 af60::3170:4ff:eff4:a4ab/64 scope link
valid_lft forever preferred_lft forever
3: br-7ac197bd041e: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 state UP
inet6 af60::42:80ff:fe52:3481/64 scope link
valid_lft forever preferred_lft forever
4: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 state UP
inet6 af60::42:6eff:fecf:5e6/64 scope link
valid_lft forever preferred_lft forever
6: veth074f8b0@if5: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 state UP
inet6 af60::7073:40ff:fe59:aad0/64 scope link
valid_lft forever preferred_lft forever
8: vethe85ed67@if7: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 state UP
inet6 af60::5c09:65ff:fe34:34f4/64 scope link
valid_lft forever preferred_lft forever
So the global IPv6 address is "2a02:8070:2982:4300:3170:4ff:eff4:a4ab".
How can retrieve this value reliably from my bash script?
I would start with
where
dev ens18
tellip
to query only forens18
-deprecated
(to be put afterls
orshow
) filter out temporary outgoing IPprimary
select primary (e.g. first IP given to interface)scope global
print only global adress (won't print link level address likefe80::
)/inet6/
tell awk to filter line withinet6
{ print $2}
print valueNote that ipv6 like
fe80::
andfd00::
are local and site address (thoses are filtered out byscope global
flag).a more XXI-th century solution would be
(with
${OTHER_ARGS}
from awk's solution above)I would say that instead of parsing
ip
output or relying on tools likejs
(which needs to be installed), you may start off thehostname -I
output which simply presents a list of all IP addresses assigned to the machine. Like this:This will show the first IPv6 address appeared in the list, even if it's link-local or site-local. You can grep them away too: