Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script check string for uppercase letter

I am trying to check a string for any Uppercase letter. my code shows NO UPPER for any input, may it be "sss", "Sss", "SSS"

if [[ "$pass" =~ [^a-zA-Z0-9] ]]
then
   echo "Upper found"
else
   echo "no upper"
fi
like image 651
Robert Vlasiu Avatar asked Oct 27 '16 22:10

Robert Vlasiu


People also ask

How do you find the uppercase of a string?

To find all the uppercase characters in a string, call the replace() method on the string passing it a regular expression, e.g. str. replace(/[^A-Z]/g, '') . The replace method will return a new string containing only the uppercase characters of the original string.

What does ${} mean in shell script?

$() – the command substitution. ${} – the parameter substitution/variable expansion.

What does $() mean in Bash?

Example of command substitution using $() in Linux: Again, $() is a command substitution which means that it “reassigns the output of a command or even multiple commands; it literally plugs the command output into another context” (Source).


1 Answers

[^a-zA-Z0-9] means anything except for a-z, i.e. lowercase letters, A-Z, i.e. uppercase letters, and 0-9, i.e. digits. sss, Sss, SSS all contain just letters, so they can't match.

[[ $password =~ [A-Z] ]]

is true if the password contains any uppercase letter.

You should set LC_ALLbefore running this kind of tests, as for example

$ LC_ALL=cs_CZ.UTF-8 bash -c '[[ č =~ [A-Z] ]] && echo match'
match
$ LC_ALL=C           bash -c '[[ č =~ [A-Z] ]] && echo match'
# exit-code: 1

[[:upper:]] should work always.

like image 114
choroba Avatar answered Sep 28 '22 15:09

choroba