Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex password validation in Bash shell

Tags:

bash

I am using Regexes in Bash Shell script. I am using the below Regex code to check password criteria : Password should be at least 6 characters long with at least one digit and at least one Upper case Alphabet. I validated in the Regex validation tools, the Regex I have formed works fine. But, it fails in Bash Shell Script. Please provide your thoughts.

echo "Please enter password for User to be created in OIM: "
echo "******Please Note: Password should be at least 6 characters long with one digit and one Upper case Alphabet******"
read user_passwd
regex="^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)\S{6,}$"
echo $user_passwd
echo $regex
if [[ $user_passwd =~ $regex ]]; then
    echolog "Password Matches the criteria"
else
    echo "Password criteria: Password should be at least 6 characters long with one digit and one Upper case Alphabet"
    echo "Password does not Match the criteria, exiting..."
    exit
fi
like image 511
Shankar Guru Avatar asked Oct 29 '25 22:10

Shankar Guru


2 Answers

BASH regex engine doesn't support lookarounds as in your regex.

You can use following shell glob check to make sure password matches your criteria:

[[ ${#s} -ge 6 && "$s" == *[A-Z]* && "$s" == *[a-z]* && "$s" == *[0-9]* ]]

It will make sure that input string $s meets all these conditions:

  • at least 6 characters long
  • has at least one digit
  • has at least one Upper case Alphabet
  • has at least one Lower case Alphabet
like image 110
anubhava Avatar answered Oct 31 '25 12:10

anubhava


I'm adding to anubhava's answer. His check worked for me but not completely. For e.g. "hello123" or "HELLO123" also passed the check, so it didn't detect case. The issue was with the locale settings, more specifically the LC_COLLATE variable. It needs to be set to "C" to consider case. But a better solution was to use character classes rather than range expressions. The explanation here helped me to solve my problem. Eventually using character classes worked for me.

[[ ${#s} -ge 6 && "$s" == *[[:lower:]]* && "$s" == *[[:upper:]]* && "$s" == *[0-9]* ]]
like image 27
dozer Avatar answered Oct 31 '25 10:10

dozer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!