Skip to content

Instantly share code, notes, and snippets.

@reorx
Created June 27, 2017 06:50
Show Gist options
  • Save reorx/bec96e0d117855dbe36505c1eaec0ddf to your computer and use it in GitHub Desktop.
Save reorx/bec96e0d117855dbe36505c1eaec0ddf to your computer and use it in GitHub Desktop.
macOS: get current active network device name, interface, mac
#!/bin/bash
services=$(networksetup -listnetworkserviceorder | grep 'Hardware Port')
while read line; do
sname=$(echo $line | awk -F "(, )|(: )|[)]" '{print $2}')
sdev=$(echo $line | awk -F "(, )|(: )|[)]" '{print $4}')
#echo "Current service: $sname, $sdev, $currentservice"
if [ -n "$sdev" ]; then
ifout="$(ifconfig $sdev 2>/dev/null)"
echo "$ifout" | grep 'status: active' > /dev/null 2>&1
rc="$?"
if [ "$rc" -eq 0 ]; then
currentservice="$sname"
currentdevice="$sdev"
currentmac=$(echo "$ifout" | awk '/ether/{print $2}')
fi
fi
done <<< "$(echo "$services")"
if [ -n "$currentservice" ]; then
echo $currentservice
echo $currentdevice
echo $currentmac
else
>&2 echo "Could not find current service"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment