Bash script to retrieve name of Ethernet Network interface
Solution 1:
Because all interfaces would displayed under /sys/class/
, such as /sys/class/net/
listing all network interfaces,
it is possible to directly use this directly search and return the exact interface name through a simple keyword like:
ls /sys/class/net | grep enp
Solution 2:
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.
Solution 3:
Assuming you got only one physical interface and not some wlan interface etc. The trick is to get the interfaces. Which are in /sys/class/net and then look where they go to.
find /sys/class/net ! -type d | xargs --max-args=1 realpath | awk -F\/ '/pci/{print $NF}'
If you got more interfaces you would have to grep lspci first:
lspci | awk '/Ethernet/{print $1}'
The whole thing would turn into:
pci=`lspci | awk '/Ethernet/{print $1}'`; find /sys/class/net ! -type d | xargs --max-args=1 realpath | awk -v pciid=$pci -F\/ '{if($0 ~ pciid){print $NF}}'
Solution 4:
I'd use ifconfig
(bit old and deprecated) tool or ip
command. Using ip route
you are having a list of available routes. Then get only line containing default with grep
and strip the unwanted characters off the string using sed
full command goes like:
ip route | grep default | sed -e "s/^.*dev.//" -e "s/.proto.*//"