4

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.

ekad
  • 14,436
  • 26
  • 44
  • 46
user2988671
  • 43
  • 1
  • 1
  • 3

2 Answers2

10

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"
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • I understand that this limits the match to ONLY the mac address, however I'm trying to solve the issue of just the bash syntax error. It doesn't like this "grouping" thing with the parentheses. – user2988671 Nov 13 '13 at 17:00
  • I have version 3.1.17(1). This is on redhat linux. Is this a feature that is only supported in 3.2? – user2988671 Nov 13 '13 at 17:06
  • Hmm can you try: `[[ "$MAC_ADDRESS" =~ "^([a-zA-Z0-9]{2}:){5}[a-zA-Z0-9]{2}$" ]]` on your Linux – anubhava Nov 13 '13 at 17:09
  • I believe this fixed it. Thank you very much! – user2988671 Nov 13 '13 at 17:22
  • 1
    Late reply but the second part of the regex should be changed to a-fA-F also instead of a-zA-Z – MappaM May 23 '16 at 08:44
3

You are actually, very close on your suggestion. Instead of going A to Z, just go A to F.

^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$
Andy
  • 49,085
  • 60
  • 166
  • 233
  • You're correct in that MAC addresses will only range to f (being hex), but that wasn't the problem I was trying to address. When doing this, I get the error "-bash: syntax error in conditional expression: unexpected token `(' " and "-bash: syntax error near `([' ". – user2988671 Nov 13 '13 at 16:59
  • 3
    @user2988671 You should be specific about what error you are getting in the question; there was no indication of *why* your attempt didn't work. – chepner Nov 13 '13 at 17:04