简体   繁体   English

如何在bash脚本中比较数组值?

[英]How to compare array values in a bash script?

I am trying to generate a random password with certain requirements. 我正在尝试生成具有某些要求的随机密码。

Minimum 8 characters 至少8个字符

Atleast 1 lowercase letter Atleast 1小写字母

atleast 1 uppercase letter 至少1个大写字母

atleast 1 number 至少1个号码

must have 1 special character 必须具有1个特殊字符

Atm I am trying to compare a random passphrase, that I generate, with the number array so that I can determine if a number exists in the generated passphrase. Atm我正在尝试将我生成的随机密码与数字数组进行比较,以便可以确定生成的密码中是否存在数字。 After getting this to work I want to use a similar check for the other arrays (lowercase, uppercase and special chars). 使此工作正常后,我想对其他数组(小写,大写和特殊字符)使用类似的检查。

However when I run my script if $phrase[1] = F and $num[1] = 1 my code will echo "fine" instead of echoing false ... the two values are not equal so I do not know why its not working? 但是,当我运行脚本时, if $phrase[1] = F and $num[1] = 1我的代码将回显"fine"而不是回显false ...这两个值不相等,所以我不知道为什么不这样做工作?

#!/bin/bash
#SET ARRAYS
num=( 0 1 2 3 4 5 6 7 8 9 )
all=( a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 )

echo

#GENERATE RANDOM PASSPHRASE
for (( i=0; i<8; i++ ))
do
phrase[$i]=${all[$RANDOM%62]}
        for (( j=0; j<10; j++ ))
        do
                #CHECK IF A VALUE FROM $NUM ARRAY IS IN $PHRASE
                if [ ${phrase[$i]}==${num[$j]} ]
                then
                echo phrase[$i]: ${phrase[$i]} #debug
                echo num[$j]: ${num[$j]}       #debug
                echo fine                     
                else
                echo false
                fi
        done
done

printf "%s" "Phrase: ${phrase[@]}" && echo
echo

echo ${num[@]}
echo

You need spaces around the == operator. 您需要在==运算符周围加空格。 Otherwise, bash only sees one large word and tests 否则,bash只会看到一个大字并进行测试

[ -n "${phrase[$i]}==${num[$j]}" ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM