Check for password strength in bash script – Code Example

Total
0
Shares

In this article we will provide you bash script code to check if password is strong or weak. We will match the protocol of – 1 uppercase letter, 1 lowercase letter, 1 number, 1 special character and at least 8 characters long. The regex is Extended Regular Expression (ERE) and not PCRE. So, it will work in bash.

Code Example –

#!/bin/bash
is_valid_password() {
    [[ "$1" =~ ^(.*[a-z]) ]] && [[ "$1" =~ ^(.*[A-Z]) ]] && [[ "$1" =~ ^(.*[0-9]) ]] && [[ "$1" =~ ^(.*[^a-zA-Z0-9]) ]] && [[ "$1" =~ ^(.){8,} ]] && echo 1
}

# This password is weak
pass="[email protected]"

# regex validation will fail
is_valid_password "$pass" || echo "weak password - $pass"

strong_pass="[email protected]"
# Contains uppercase, lowercase, special char, number, more than 8 chars
is_valid_password "$strong_pass" || echo "weak pass - $strong_pass"

# Output: 
# weak password - [email protected]
# [email protected]

Live Demo

Open Live Demo