如何使用Shell Script检查用户输入值是大写,小写还是数字?

我试图写一个shell script来读取用户输入数据,并检查输入值是大写,小写还是其他。但是我写的只是检查单个字符

这是我写的:

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

如何使它读取除单个字符以外的长字符串,并相应地获取输出?

xjj070324why 回答:如何使用Shell Script检查用户输入值是大写,小写还是数字?

您可以通过多种方式进行操作,这里有一个:

#!/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
,

在使用shopt -s extglob之前,可以使用+([[:upper:]])来匹配由一个或多个大写字母组成的字符串。

来自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

例如,使用+([[:upper:][:digit:] .])来匹配一个或多个{大写字母,数字,空格,点}。考虑使用POSIX标准中定义的其他一些以下类:
alnum alpha ascii blank cntrl digit graph lower print punct space upper word xdigit

证明有效(只是对示例的测试):

shopt -s extglob; case "1A5. .Q7." in (+([[:upper:][:digit:] .])) echo "it works";; esac
本文链接:https://www.f2er.com/3144498.html

大家都在问