Thursday, October 27, 2022

[SOLVED] BASH regex match MAC address

Issue

I'm trying to allow a user to only input a valid mac address (i.e. 0a:1b:2c:3d:4e:5f), and would like it to be more succinct than the expanded form:

[[ $MAC_ADDRESS =~ [a-zA-Z0-9][a-zA-Z0-9]:[a-zA-Z0-9][a-zA-Z0-9]:[a-zA-Z0-9][a-zA-Z0-9]:[a-zA-Z0-9][a-zA-Z0-9]:[a-zA-Z0-9][a-zA-Z0-9] ]]

Is there a way to do it like this?

[[ $MAC_ADDRESS =~ ([a-zA-Z0-9]{2}:){5}[a-zA-Z0-9]{2} ]]

Essentially, I'd like to create a "group" consisting of two alphanumeric characters followed by a colon, then repeat that five times. I've tried everything I can think of, and I'm pretty sure something like this is possible.


Solution

I would suggest using ^ and $ to make sure nothing else is there:

[[ "$MAC_ADDRESS" =~ ^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$ ]] && echo "valid" || echo "invalid"

EDIT: For using regex on BASH ver 3.1 or earlier you need to quote the regex, so following should work:

[[ "$MAC_ADDRESS" =~ "^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$" ]] && echo "valid" || echo "invalid"

Update:

To make this solution compliant with older and newer bash versions I suggest declaring regex separately first and use it as:

re="^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$"
[[ $MAC_ADDRESS =~ $re ]] && echo "valid" || echo "invalid"


Answered By - anubhava
Answer Checked By - Timothy Miller (WPSolving Admin)