Detecting the name of a network device in bash?

I'm trying to drum up a hack that will output the name of active network devices on one's computer via bash. I'm making it for work. How do I go about doing this? I don't want to just plainly use "wlan0" or "eth0" or any of that generic crap because some OSes use different names (Like pfSense for example).


Solution 1:

It depends what you mean by 'active' - if you just want to see the names of all the network devices on the system, you can look at the contents of the /sys/class/net directory e.g.

$ ls /sys/class/net
eth0  lo  wlan0

To see the status, you could use the ip command on any link objects - you can parse the output to get the particular fields you want e.g. to see just the device name and state

$ ip -o link show | awk '{print $2,$9}'
lo: UNKNOWN
eth0: DOWN
wlan0: UP

If you are running a modern desktop version of Ubuntu (with interfaces managed by the network-manager service), then you should be able to get a similar device status list using nmcli

$ nmcli dev status
DEVICE     TYPE              STATE
wlan0      802-11-wireless   connected
eth0       802-3-ethernet    unavailable

or, to limit the output to particular fields in a way that's more easily used in a script

$ nmcli --terse --fields DEVICE,STATE dev status
wlan0:connected
eth0:unavailable

If you are using network-manager, you could also access device and connection properties via DBUS - see for example Dbus Tutorial - Fun with Network Manager

Solution 2:

You can use ifconfig to detect the active network devices, for a little smaller output use ifconfig -s. ifconfig prints the active interfaces, with -a you can print all interfaces that are recognized by the system as network interfaces.

Or use ip addr.