but whenever I try to run it with the correct variables, it outputs "[: =: unary operator expected" and quits.
That's because you have an unquoted/empty variable inside the [
, either quote your variables or use [[
which is safer and more robust.
while [ $i = "PASSWORD" ]
The value of $i
is empty there is no way a user can give the value/input, so it will fail
Edit: As mentioned by @William Pursell
, Regardless which test you are using, it still has some pitfall, the lesson here is to sanitize/validate the input, e.g. test it if it is indeed a digit, if it is not empty and so on.
Try this, It might do what you wanted.
#!/usr/bin/env bash
clear
p="PASSWORD"
read -rp "Please enter your password: " input ##: Ask the user to enter the password
until [[ $p == "$input" ]]; do ##: The loop will continue until both vars matches
clear
printf 'Please try again! %s does not match..\n' >&2 "$input"
read -rp "Please enter your password: " input
done
##: If it matches print a message and the value of input
printf '%s is a match!\n' "$input"