Home > Net >  Bash Password validator
Bash Password validator

Time:05-24

I have stuck with my bash code. and needed some help. I trying to write bash code that : Length – minimum of 10 characters. Contain both alphabet and number. Include both the small and capital case letters. Color the output green if it passed the validation and red if it didn’t. Return exit code 0 if it passed the validation and exit code 1 if it didn’t., the problem that can be resolved for me is that code does not check upper and lower case. and have exit 0, which means the password ok in all cases.

 # Color for Output
Warning='\033[0;31m'        # Red
Success='\033[0;32m'      # Green
NC="\033[0m"            # No Color

password=$1
len="${#password}"
if test $len -ge 4 ; then

echo "$password" | grep -eq [[:digit:]]
if test $? -eq 1 ; then

echo "$password" | grep -e [[:upper:]]
if test $? -e 1 ; then

echo "$password" | grep -e [[:lower:]]  
if test $? -e 1 ; then

printf "${Success}Strong password!$1\n"
else
 echo "weak password include lower case char"
fi
else
 echo "weak password include capital char" 
fi
else
echo && echo $?
printf "${Success}Strong password!$1\n"
fi
else
echo $?
printf ${Warning}"Try again... \nPassword must have at least 10 characters.$1\n"
fi

CodePudding user response:

In bash, within the [[ ... ]] conditional, the == and != operators do pattern matching. And bash patterns can include POSIX character classes.

error() {
    echo "$*" >&2
    exit 1
}

password=$1

if (( ${#password} < 10 )); then
    error "Too short"
elif [[ $password != *[[:digit:]]* ]]; then
    error "Does not contain a digit"
elif [[ $password != *[[:lower:]]* ]]; then
    error "Does not contain a lower case letter"
elif [[ $password != *[[:upper:]]* ]]; then
    error "Does not contain an upper case letter"
fi

echo "OK"
exit 0

That can be written more concisely:

(( ${#password} >= 10 ))         || error "Too short"
[[ $password == *[[:digit:]]* ]] || error "Does not contain a digit"
[[ $password == *[[:lower:]]* ]] || error "Does not contain a lower case letter"
[[ $password == *[[:upper:]]* ]] || error "Does not contain an upper case letter"
echo OK

[[ ... ]] also has the =~ regular-expression matching operator (there is no !~ negated matching operator):

# it contains a digit, or error
[[ $password =~ [[:digit:]] ]] || error "Does not contain a digit"
  • Related