How to get macOS Wi-Fi device name programmatically in Bash script? bash% networksetup -listnetworkserviceorder
An asterisk (*) denotes that a network service is disabled.
(1) SAMSUNG Modem
(Hardware Port: Modem (SAMSUNG_MDM), Device: SAMSUNG_MDM)

(2) Ethernet
(Hardware Port: Ethernet, Device: en0)

(3) FireWire
(Hardware Port: FireWire, Device: fw0)

(4) Wi-Fi
(Hardware Port: Wi-Fi, Device: en1)

(5) Bluetooth PAN
(Hardware Port: Bluetooth PAN, Device: en2)


This is good for reading but how do I get 'en1' programmatically in a Bash script so I can use the device name in a cron job?
In your question I know you used networksetup -listnetworkserviceorder however I'd use networksetup -listallhardwareports instead as it's easier to parse the output using awk, by itself, with a minimum of coding so as to avoid multiple pipes using several other commands as offered in the other answer and should be robust enough to produce consistent output until Apple changes the output format of networksetup -listallhardwareports, if they ever do.

As an example on my system, networksetup -listallhardwareports shows the following:

$ networksetup -listallhardwareports

Hardware Port: Bluetooth DUN
Device: Bluetooth-Modem
Ethernet Address: N/A

Hardware Port: Display Ethernet
Device: en3
Ethernet Address: xx:xx:xx:xx:xx:xx

Hardware Port: Display FireWire
Device: fw0
Ethernet Address: xx:xx:xx:xx:xx:xx

Hardware Port: Wi-Fi
Device: en0
Ethernet Address: xx:xx:xx:xx:xx:xx

Hardware Port: Bluetooth PAN
Device: en2
Ethernet Address: N/A

VLAN Configurations
===================
$ 


Looking at the relevant lines of output:

Hardware Port: Wi-Fi
Device: en0


The easiest way to get en0, in this example is:

networksetup -listallhardwareports | awk '/Wi-Fi/{getline; print $2}'


It can be assigned to a variable:

wifiDevice="$(networksetup -listallhardwareports | awk '/Wi-Fi/{getline; print $2}')"


You can then use $wifiDevice later in the script to represent en0, in this example.

Obviously on your system, based on the output in your question, $wifiDevice would be: en1



If you want to use networksetup -listnetworkserviceorderthen you can use awk, by itself, in this manner:

networksetup -listnetworkserviceorder | awk '{gsub(/\)/, "")}/Wi-Fi, Device/{print $5}'


However, I'd use my first example over this.



I'd also stay away from using system_profiler in this case, as it takes considerably longer for the output to be generated then when using networksetup.