简体   繁体   中英

How to compare array values in a bash script?

I am trying to generate a random password with certain requirements.

Minimum 8 characters

Atleast 1 lowercase letter

atleast 1 uppercase letter

atleast 1 number

must have 1 special character

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. 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?

#!/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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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