Bash script check string for uppercase letter

亡梦爱人 提交于 2021-02-04 18:09:05

问题


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

回答1:


[^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.




回答2:


Your regex is wrong. Use [A-Z] or [:upper:].

https://en.wikipedia.org/wiki/Regular_expression




回答3:


I had trouble with this script no matter how I ran it, until I changed it to let my input string be $1, and then set pass=$1. I also changed the regex a bit. What I finally got to work correctly is below. Then I could run bash (script) John and get a valid response. Hope this helps.

pass=$1
if [[ "$pass" =~ ^[A-Z] ]]
then
   echo "Upper found"
else
   echo "No Upper"
fi


来源:https://stackoverflow.com/questions/40294902/bash-script-check-string-for-uppercase-letter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!