1

I am trying to validate database name like command.sh databaseName with-in given regex as parameter using bash script.

For example

dataBaseNameIsValid
data-BaseNameIsValid
-dataBaseNameIsNotValid
dataBaseNameIsNotValid-

And the following code is working:

if [ -z $1 ]; then
    echo "No database name given"
    exit 1
fi

DATABASENAME=$1

# check the DATABASENAME is roughly valid!
DATABASE_PATTERN="^([[:alnum:]]([[:alnum:]\-]{0,61}[[:alnum:]]))$"

if [[ "$DATABASENAME" =~ $DATABASE_PATTERN ]]; then
    DATABASENAME=`echo $DATABASENAME | tr '[A-Z]' '[a-z]'`
    echo "DATABASENAME: " $DATABASENAME
else
    echo "invalid DATABASENAME"
    exit 1
fi

Now I want to introduce underscore _ as valid char as well, what I did, I have added _ score to my regex like this:

DATABASE_PATTERN="^([[:alnum:]]([[:alnum:]\-_]{0,61}[[:alnum:]]))$"

This return invalid DATABASENAME.

What I might doing wrong here?

Maytham Fahmi
  • 26,353
  • 12
  • 100
  • 121

1 Answers1

2

The dash needs to be last (and the backslash doesn't help here). Just switch the order between - and _ to get a well-defined enumeration.

(The dash can also be the very first character inside a character class, or immediately after the negation operator in a negated character class.)

tripleee
  • 158,107
  • 27
  • 234
  • 292