BhagyaKolitha Jayalath
BhagyaKolitha Jayalath

Reputation: 103

How to check of the user input value is Upper case, Lower case or a digit using Shell Script?

I am trying to write a shell script to read user input data and check if the input value is either Upper Case, Lower Case or anything else. But what I wrote is only checking a single character

Here is what I wrote:

printf 'Please enter a character: '
IFS= read -r c
case $c in
  ([[:lower:]]) echo lowercase letter;;
  ([[:upper:]]) echo uppercase letter;;
  ([[:alpha:]]) echo neither lower nor uppercase letter;;
  ([[:digit:]]) echo decimal digit;;
  (?) echo any other single character;;
  ("") echo nothing;;
  (*) echo anything else;;
esac

How can I make it read a long String other than a single character and get the output accordingly?

Upvotes: 2

Views: 1545

Answers (2)

Mika Feiler
Mika Feiler

Reputation: 516

Preceding your use with shopt -s extglob, you can use +([[:upper:]]) to match a string composed of one or more uppercase letters.

From man 1 bash:

       If the extglob shell option is enabled using the shopt builtin, several
       extended  pattern  matching operators are recognized.  In the following
       description, a pattern-list is a list of one or more patterns separated
       by a |.  Composite patterns may be formed using one or more of the fol‐
       lowing sub-patterns:

              ?(pattern-list)
                     Matches zero or one occurrence of the given patterns
              *(pattern-list)
                     Matches zero or more occurrences of the given patterns
              +(pattern-list)
                     Matches one or more occurrences of the given patterns
              @(pattern-list)
                     Matches one of the given patterns
              !(pattern-list)
                     Matches anything except one of the given patterns

Use, for example, +([[:upper:][:digit:] .]) to match one or more {uppercase letters, digits, spaces, dots}. Consider using some of the other following classes defined in the POSIX standard:
alnum alpha ascii blank cntrl digit graph lower print punct space upper word xdigit

Proof (just a test on an example) that it works:

shopt -s extglob; case "1A5. .Q7." in (+([[:upper:][:digit:] .])) echo "it works";; esac

Upvotes: 1

Jaime S
Jaime S

Reputation: 1698

You can do it in many ways, here you have one:

#!/bin/bash

read -p "Enter something: "  str
echo "Your input is: $str"

strUppercase=$(printf '%s\n' "$str" | awk '{ print toupper($0) }')
strLowercase=$(printf '%s\n' "$str" | awk '{ print tolower($0) }')

if [ -z "${str//[0-9]}" ]
then
    echo "Digit"
elif [ $str == $strLowercase ]
then
    echo "Lowercase"
elif [ $str == $strUppercase ]
then
    echo "Uppercase"
else
    echo "Something else"
fi

Upvotes: 1

Related Questions