You know that to read input from the user, you use read
command. But when you use -s
option with read
command, it does not display the characters entered by the user on the screen and making it suitable for reading password. You can use -s
option with or without -p
option.
#Bash Shell script to input password from the user echo -n "Enter a password: " read -s firstpassword echo read -s -p "Retype a password: " secondpassword echo if [ $firstpassword == $secondpassword ]; then echo "Both passwords are same." else echo "You have entered different passwords." fi
Output of the above program
Enter a password: Retype a password: Both passwords are same.
Explanation of the above code-
echo -n "Enter a password: " read -s firstpassword echo
echo
statement is used to display the message. After this, read
with -s
option is for reading the password from the user. echo
with no message is used to provide new line.
read -s -p "Retype a password: " secondpassword echo
Here, we have used -s
and -p
options of read
command to display message and also reading password from the user.
if [ $firstpassword == $secondpassword ]; then echo "Both passwords are same." else echo "You have entered different passwords." fi
Here, we are checking that both the entered passwords are same or not. If they are same, then we will display "Both passwords are same" otherwise we will display "You have entered different passwords."