Regex password validation in Bash shell

Viewed 10103

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
2 Answers

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]* ]]
Related