'bash validating user name with regex

from the useradd man page I should be able to verify if a filed red from a file is a valid username with:

if [ $1 =~ [a-z_][a-z0-9_-]*[$]? ]; then

white space is not allowed, but is not detected, first character is limited to a-z and underscore but again, it did not detected correctly, also Fedora has a limit of 16 char. So modified it to something like that:

GroupeEtUsagerValide() {
    if [ ${#1} -gt 16 ];then
        return 1
        elif [[ $1 =~ ^[[:lower:]_][[:lower:][:digit:]_-]{2,15} ]]; then
            return 0
        else
            return 1
    fi 
}

white space was detected, but not anymore, I must have change something and can't find it This is a function $1 is a value read from a file



Solution 1:[1]

Some notes:

  • Regex matching (using ERE syntax) is available only in [[ ]], not [ ] (as used in your first code sample).
  • The default return value of a function is that of the last command in it. Thus the if is entirely unneeded.
  • If you don't anchor your regex explicitly, with ^ at the beginning and $ at the end, it won't be anchored at all. Your current code doesn't have an anchor at the end, so it would accept anything with at least three valid characters even if those characters are followed by a space.

isValidUsername() {
  local re='^[[:lower:]_][[:lower:][:digit:]_-]{2,15}$'
  (( ${#1} > 16 )) && return 1
  [[ $1 =~ $re ]] # return value of this comparison is used for the function
}

To use this:

testValidUsername() {
  if isValidUsername "$1"; then
    echo "$1 is a valid username"
  else
    echo "$1 is not a valid username"
  fi
}

testValidUsername abcdefg
testValidUsername 1234567
testValidUsername a123456
testValidUsername 012345678901234567890

...and output, as expected:

abcdefg is a valid username
1234567 is not a valid username
a123456 is a valid username
012345678901234567890 is not a valid username

Solution 2:[2]

I was pretty close at the beginning, the man page was right, I was just missing the anchors.

if [[ $usager =~ ^[[:lower:]_][[:lower:][:digit:]_-]*[$]?$ ]]; then

Solution 3:[3]

Validate Username (regex):

  • ^[a-z0-9_-]{3,15}$ Usernames between 3 and 15 characters

Usage Example:

username="John"
if [[ "$username" =~ ^[a-z0-9_-]{3,15}$ ]]; then
  echo "Username is valid"
fi

See Ubuntu Regex Basics blog to learn more.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 heemayl
Solution 3 Benny