大网数据广告活动
服务器运维问答

Bash script to retrieve name of Ethernet Network interface

· 52CE 我爱测

In Ubuntu 16.04 I made a script to dinamically configure IP address of the wired ethernet interface based on certain parameters. Now the problem is that in my script I assume that the name is eth0, but this is not always true.. a…

问题原文

原帖链接 · rok · CC BY-SA 4.0

In Ubuntu 16.04 I made a script to dinamically configure IP address of the wired ethernet interface based on certain parameters. Now the problem is that in my script I assume that the name is eth0, but this is not always true.. assuming that I have only one wired network interface (not necessary plugged) but I can have also a wireless interface, how can I retrieve its name (just the wired one)?

with ifconfig command I get:

enp7s0    Link encap:Ethernet  HWaddr fc:3f:db:a2:6d:46  
          inet addr:192.168.0.101  Bcast:192.168.0.255  Mask:255.255.255.0
          inet6 addr: fe80::149f:3103:af2f:1ec5/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:6784 errors:0 dropped:0 overruns:0 frame:0
          TX packets:7493 errors:1 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:4565079 (4.5 MB)  TX bytes:827825 (827.8 KB)

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:8037 errors:0 dropped:0 overruns:0 frame:0
          TX packets:8037 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1 
          RX bytes:2261250 (2.2 MB)  TX bytes:2261250 (2.2 MB)

wlp19s0   Link encap:Ethernet  HWaddr c8:ff:28:93:26:32  
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:180463 errors:0 dropped:0 overruns:0 frame:0
          TX packets:121275 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:229823414 (229.8 MB)  TX bytes:15675806 (15.6 MB)

What I want is:

enp7s0

已采纳解答

原帖链接 · Valentin Bajrami · CC BY-SA 4.0

If you want to exclude interfaces like vir , loopback and wl(wireless) then the following should do the trick.

ip link | awk -F: '$0 !~ "lo|vir|wl|^[^0-9]"{print $2;getline}'

Here we use colon as delimiter -F: then check if the row $0 does not match a certain string using regular expression.

Update: Using the -brief flag as suggested in the comment, the command changes to:

ip -br l | awk '$1 !~ "lo|vir|wl" { print $1}'

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2017-04-06)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。