#!/bin/bash
password=$1
if [[ $# -gt 1 || $1 = "-h" ]]; then
echo 'Usage: pw | pw -h | pw password'
echo "Note: Valid passwords must be between 8-16 characters long.
contain at least 1 digit
contain at least 1 lowercase letter
contain at least 1 uppcase letter
contain one of @ # $ % & * + - ="
fi
if [[ $# -lt 1 ]]; then
regex='0-9A-Z@*+#$%&a-z'
password=$( cat /dev/urandom | tr -dc '0-9A-Z@*+#$%&a-z' | head -c $(( 8 + $RANDOM % 8 )))
check=$( echo $password | grep -o ['@*+#$%&'] | wc -m )
while [[ $check -gt 2 || $check -lt 1 ]]
do
password=$( cat /dev/urandom | tr -dc '0-9A-Z@*+#$%&a-z' | head -c $(( 8 + $RANDOM % 8 )))
check=$( echo $password | grep -o ['@*+#$%&'] | wc -m )
done
echo $password
fi
if [[ $# = 1 ]]; then
password=$1
echo "$password" | grep [A-Z][a-z]
if [[ $? = 1 ]]; then
echo "Password must contain at least one upper or lowercase characer"
exit 2
fi
echo "$password" | grep [0-9]
if [[ $? = 1 ]]; then
echo "Password must contain at least one digit"
exit 3
fi
if [[ `echo "$password" | grep -o ['@#$%&*+-'] 2>/dev/null` -gt 2 ]]; then
echo "You must only use one special character"
exit 4
fi
if [[ `echo "$password" | grep -o ['\@\#\$\%\&\*\+\-'] 2>/dev/null` -lt 1 ]]; then
echo "Password must contain at least one special character"
exit 5
fi
woc=$( echo "$password" | wc -m )
if [[ $woc -lt 8 || $woc -gt 16 ]]; then
echo "Password must be between 8 and 16 characters"
exit 6
fi
echo "$1 is a valid password"
fi
此脚本的第一部分工作正常,并生成一个8-16个字符长的随机密码,只有一个特殊字符。问题出现在第40行和第45行,两者都给出了同样的错误"语法错误:期待操作数" [特殊字符]"。我尝试使用$?创建变量并调用它们?变量来检查输出等等。不幸的是,即使脚本运行正确,此错误也会保持一致。
答案 0 :(得分:2)
我修复了代码,这是一个简单的错误。我忘了包含wc -m。
if [[ `echo "$password" | grep [\@\#\$\%\&\*\+\-] | wc -m` -lt 2 ]]