0

Asterisk is not accepting in my case statement, My case statement is below, i tried escaping with \ " ',but no luck. can you correct me where i am wrong here.

case $tdat in
    *['\*''!'@#$%^"'*'"-+]* )  echo "Special charters are not allowed" 
     usage
     exit 100 ;;
3
  • 2
    You may want to use the pattern *[[:punct:]]* instead. To match a * anywhere in a string, you may use *[*]* or *\** or *'*'* or *"*"*. Not turning this into an answer until we know what's in $tdat and what the user is trying to achieve.
    – Kusalananda
    Feb 16 at 14:33
  • 1
    Another idea would be to use a pattern that employs the characters that you do want the string to contain, but inverted: *[![:alnum:][:blank:]_]* (matches a character that isn't an alphanumeric, space, tab, or underscore, somewhere in a string). Again, we don't quite know what you're after.
    – Kusalananda
    Feb 16 at 14:55
  • @Kusalananda $tdat date in mmddyyyy format. Used this ""* in case and it is working Fine ,Thanks Alot!!!!
    – Renga
    Feb 16 at 14:59
1

According to comments, you want to validate that a string in $tdat is a date in MMDDYYYY format.

Your current issue is to write out a diagnostic message and exit if the given string contains a variety of illegal characters, mostly punctuation characters.

I would personally use *[[:punct:]]* to try to see whether a string contains a punctuation character. The [:punct:] character class is the set !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~.

In this particular case, given that we want the string in $tdat to be eight digits, exactly:

case $tdat in
    *[![:digit:]]*)
        echo 'Incorrect, contains non-digit'
        exit 1
        ;;
    ????????)
        echo 'Correct, contains eight digits exactly'
        ;;
    *)
        echo 'Incorrect, contains some other number of digits, not eight'
        exit 1
esac

In the bash shell, you could obviously also use a regular expression test:

if [[ $tdat =~ ^[[:digit:]]{8}$ ]]; then
    echo 'Correct, contains eight digits exactly'
else
    echo 'Incorrect, contains something that is not just eight digits'
    exit 1
fi

After deciding that $tdat is a string of eight digits, the next task is to figure out whether it's a valid date. This is outside the scope of this question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.