1

I have been working on a bash scripts which takes a single parameter as input from the user.

I have to verify that this input has (at least) a file extension suffix [ex: '.com', '.ca', etc] AND that it doesn't have an empty name before that suffix.

I have given multiple tries at trying to set up regex validation and have come up with this regex validation statement (where $1 is what the user input): if [[ $1 =~ ^.+\.[A-z0-9]+$ ]].

I thought that this string would be able to match a string starting with at least 1 character, followed by a literal dot ('.') and finally catching at least one alphabet or number character.

Here's the full code on validating user input for anyone curious.

domainName="";
    if [ $# -eq 1 ]; then
        if [[ $1 =~ ^.+\.[A-z0-9]+$ ]]; then
            domainName=$1;
            printf "The domain name is: \"%s\"\n" $domainName;
        else
            printf "The domain name needs at least a suffix (ex: '.com', '.ca', etc)\n";
        fi
    elif [ $# -le 0 ]; then
        printf "You need to give me a domain name to set up!\n";
        exit 1;
    else
        printf "You cannot have more than 1 domain set up at a time!\n";
        exit 1;
    fi

If anyone has any ideas on what is happening and how I could fix this, please share your knowledge :)

Thanks in advance!

Raspberry
  • 33
  • 5

1 Answers1

0

Problem is A-z in your character class [A-z0-9] which matched many more characters between A and z in ASCII table such as: [, \, ] etc.

Use this:

[[ $1 =~ ^.+\.[A-Za-z0-9]+$ ]]

Or even better:

[[ $1 =~ ^.+\.[[:alnum:]]+$ ]]
anubhava
  • 761,203
  • 64
  • 569
  • 643