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
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:
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]* ]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With