How to check if argument has one character in shell

I am trying to make a script to check if the argument has one uppercase or lowercase letter, or if something else (digit or word, for example.)

So far this has been done:

if echo $1 | egrep -q '[AZ]'; then echo "Uppercase"; elif echo $1 | egrep -q '[az]'; then echo "Lowercase"; else echo "FAIL"; fi 

It is necessary to make him dump me not only if it is not a letter, but if I insert a word or 2 letters.

+4
source share
3 answers

You were very close!

 if echo $1 | egrep -q '^[AZ]$'; then echo "Uppercase"; elif echo $1 | egrep -q '^[az]$'; then echo "Lowercase"; else echo "FAIL"; fi 
  • I just added special characters ^ and $ , which means, respectively, the beginning of the line and the end of the line
  • no need egrep there, grep enough
+1
source

Use case :

 case "$1" in [az]) echo First argument is a lower case letter;; [AZ]) echo First argument is an upper case letter;; *) echo First argument is not a single letter;; esac 
+2
source

If you use bash,

 if [[ $1 == [[:upper:]] ]]; then echo "$1 is a single capital letter" elif [[ $1 == [[:lower:]] ]]; then echo "$1 is a single lowercase letter" else echo "$1 is not a letter or is more than 1 char" fi 

The double parameter is equal to the bash value to match the pattern on the right side.

+1
source

Source: https://habr.com/ru/post/1447364/


All Articles