>_ IzzyLab

Hands-on task

This task is step 23 of the course “Regular expressions”

MAC address validation

medium~7 min

Write /usr/local/bin/ismac: if the argument is a valid MAC address (XX:XX:XX:XX:XX:XX, hex) — exit 0, otherwise 1. The script is easiest to write in the Editor tab above the terminal: /usr/local/bin is open there next to /root.

What you'll practise:
  • bash
  • regular expressions
  • =~ operator
  • grouping
  • exit codes

Topic breakdown

Format validation in bash is done with the built-in =~ operator inside [[ ... ]] — this is extended regex without external utilities. The key idea is to assemble the pattern from a repeating block: a MAC address is five times "a pair of hex digits and a colon" plus a final pair without a colon. The repetition is described by wrapping the block in parentheses and applying the counting quantifier to the whole group. The ^ and $ anchors are mandatory, otherwise the check passes for a string where the valid piece is only part of a long string. The script returns the code of the comparison itself; don't forget the shebang and the executable bit.

What's checked

  1. Script is executable
  2. Valid MAC accepted
  3. Malformed MAC rejected
  4. Malformed formats rejected

What it looks like