Reputation: 175
I am attempting to create a bash script that creates an array of the Ethernet device names on my PC and not wireless card. I want to have a list of the names so I can later iterate over them.
For example - Assume I have two ethernet NICs - enp2s0 and enp3s0 and a wireless card - wlp4s0
From lscpi
I would see
02:00.0 Ethernet controller: <truncated>
03:00.0 Ethernet controller: <truncated>
04:00.0 Network controller: Intel Corporation Wireless
Similarly ip a
shows
1: lo: <truncated>
2: enp2s0: <truncated>
3: enp3s0: <truncated>
4: wlp4s0: <truncated>
How can I create an array of the names so I can iterate over them?
enp2s0
enp3s0
I have figured out how to find the first NIC using
NIC=$(basename $(udevadm info -e | grep "DEVPATH=.*$(lspci | grep -m 1 Ethernet | cut -f 1 -d\ )/net" | cut -f 2 -d\ ))
But I cannot figure out how to loop this approach. Any suggestions how I can do this in bash?
Thanks
Densha
Upvotes: 2
Views: 3302
Reputation: 27205
nmcli
has an output which can be be parsed easily, but you may have to install it first.
Example output of nmcli device
:
DEVICE TYPE STATE CONNECTION
eno1 ethernet connected wired connection
wlp2s0 wifi unavailable --
lo loopback unmanaged --
To extract only the names of ethernet devices use
nmcli device | awk '$2=="ethernet" {print $1}'
In this example the output will be eno1
. You can use the command in a loop as usual.
Here we assume the first column to be free of special symbols like *[]?
so that we can use the simple and portable (but potentially unsafe) construct for variable in $(command)
,
for device in $(nmcli device | awk '$2=="ethernet" {print $1}'); do
# stuff
done
Upvotes: 4
Reputation: 175
Thanks with the suggestions I modified my original to
for DEV in $(lspci | grep Ethernet | cut -f 1 -d\ )
do
NIC=$(basename $(udevadm info -e | grep "DEVPATH=.*$DEV/net" | cut -f 2 -d\ ))
echo $NIC
done
Thanks for the suggestions
Upvotes: 0
Reputation: 4574
for f in $(ip a | grep enp | awk '{print $2}' | cut -d":" -f1)
do
<something with $f>
done
For devices that don't start with "enp" the below is an alternative :
for f in $(ip a | grep -B1 "ether" | grep -v ether | awk '{print $2}' | cut -d":" -f1)
do
<something with $f>
done
Upvotes: 0