'How to safely confirm a password by entering it twice in a bash script
I would like to create a bash script where a user can choose a username, a password and confirm the password by entering it twice. If the passwords do not match the user should be prompted to enter it again. If the passwords match, the script should create a passwordhash, otherwise ask again until it is correct.
So far I have the code below but I am not sure if this is the right way to do this. Is there a problem with the following bash script?
# read username
read -p "Username: " username
# read password twice
read -s -p "Password: " password
echo
read -s -p "Password (again): " password2
# check if passwords match and if not ask again
while [ "$password" != "$password2" ];
do
echo
echo "Please try again"
read -s -p "Password: " password
echo
read -s -p "Password (again): " password2
done
# create passwordhash
passwordhash=`openssl passwd -1 $password`
# do something with the user and passwordhash
Solution 1:[1]
A way to reduce verbosity:
#!/bin/bash
read -p "Username: " username
while true; do
read -s -p "Password: " password
echo
read -s -p "Password (again): " password2
echo
[ "$password" = "$password2" ] && break
echo "Please try again"
done
Solution 2:[2]
Don't forget a continue, so the while loop will start over on two different passwords.
while [ -z "$password" ]; do
echo "Please enter a password: "
read -s first
read -s -p "Retype a password: " second
if [ $first == $second ];
then
password=$first
echo "Both passwords are the same. Continuing.."
else
echo "You have entered different passwords. Try again.."
continue
fi
break
done
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | joanis |
