How to check if input string matches a specific format?
The lazy way is just to run
if [[ $mac_address == ??:??:??:??:??:?? ]]; then echo Heureka; fi
but this doesn't check whether it's a hex string. So if this is important
if [[ $mac_address =~ ^[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]$ ]]; then echo Heureka; fi
might be better. The later can be shortened to
if [[ $mac_address =~ ^([[:xdigit:]]{2}:){5}[[:xdigit:]]{2}$ ]]; then
echo Heureka;
fi
If the pattern matches I don't see a need to check for the correct length as well.
[[ $mac_address: =~ ^([[:xdigit:]]{2}:){6}$ ]]
I changed the name of the variable so that it consisted of legal characters, then used the =~
test operator to compare the value to the extended regular expression matching: at the beginning of the string ^
, "2 hex digits and a colon" 5 times, followed by 2 hex digits, ending the string $
:
#!/bin/bash
read -p "enter mac-address " mac_address
if [[ $mac_address =~ ^([[:xdigit:]][[:xdigit:]]:){5}[[:xdigit:]][[:xdigit:]]$ ]]
then
echo good
else
echo bad
fi