#!/bin/sh
# Universal MAC Address Grabber for Linux & BSD
# Compatible with POSIX sh (bash, zsh, dash, ksh)
# Helper function to clean up and print in a uniform format
print_mac() {
# Takes "interface mac" and prints if MAC looks valid (matches 6 hex pairs)
if echo "$2" | grep -iqE '^([0-9a-f]{2}[:-]){5}[0-9a-f]{2}$'; then
printf "%-15s %s\n" "$1" "$2"
fi
}
echo "Detected Network Interfaces & MAC Addresses:"
echo "-------------------------------------------"
# 1. Try sysfs method (Linux system, reliable, no binary dependencies)
if [ -d /sys/class/net ]; then
for iface in /sys/class/net/*; do
ifname=$(basename "$iface")
# Skip loopback
if [ "$ifname" != "lo" ] && [ -f "$iface/address" ]; then
mac=$(cat "$iface/address")
print_mac "$ifname:" "$mac"
fi
done
exit 0
fi
# 2. Try 'ip' command (Modern Linux / iproute2)
if command -v ip >/dev/null 2>&1; then
ip -o link show | awk '$2 != "lo:" {print $2, $(NF-2)}' | tr -d ':' | while read -r dev mac; do
# Extract interface name properly (strip trailing colon or @vlan)
clean_dev=$(echo "$dev" | cut -d: -f1 | cut -d@ -f1)
# Fetch actual link/ether MAC
actual_mac=$(ip link show "$clean_dev" 2>/dev/null | awk '/link\/ether/ {print $2}')
print_mac "$clean_dev:" "$actual_mac"
done
exit 0
fi
# 3. Try 'ifconfig' method (BSD / macOS / Legacy Linux / SLES minimal)
if command -v ifconfig >/dev/null 2>&1; then
# ifconfig format varies between BSD and Linux
ifconfig -a | awk '
/^[a-zA-Z0-9_-]+/ {
iface=$1
sub(":", "", iface)
}
# BSD / macOS / Solaris syntax (ether / address)
/ether|hwaddr|address/ {
for (i=1; i<=NF; i++) {
if ($i ~ /^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$/) {
if (iface != "lo" && iface != "lo0") {
print iface ":", $i
}
}
}
}
' | while read -r dev mac; do
print_mac "$dev" "$mac"
done
exit 0
fi
echo "Error: Could not determine network interfaces (missing sysfs, ip, and ifconfig)." >&2
exit 1