Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to safely confirm a password by entering it twice in a bash script

Tags:

bash

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
like image 584
Passuf Avatar asked Mar 07 '14 11:03

Passuf


1 Answers

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
like image 157
Juan Diego Godoy Robles Avatar answered Nov 15 '22 07:11

Juan Diego Godoy Robles