MAC Address Validation Regex with egrep

I needed an easy way to validate a MAC address in a bash script that generated a unique hostname based on the MAC address of the system. This gem did the trick:

echo "00:11:24:3e:a5:78" | egrep "^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$"

In the event that there was a problem getting the MAC address (e.g., faulty NIC or unstable device driver), I generate a random hostname instead of basing the hostname generation on the MAC. Here's how I validated the MAC in the script:

if [ `echo $ACTIVE_INTERFACE_MAC | egrep "^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$"` ]; then
    # generate unique hostname based on MAC
else
    # generate random-character hostname
fi

Write a Comment

Comment