Bash Read Password

Bash Read Password – In this Bash Tutorial, we shall learn to read username and password from user, with Password being not echoed back to shell.

Bash Read Username and Password without echoing

We shall use read command with following options,

read -p PROMPT <variable_name>  displays PROMPT without a new line and echoes input read from user, character by character. The input is read to bash variable. This option p  is suitable for reading Username.

read -sp PROMPT <variable_name>  displays PROMPT without a new line and reads input from user in silent mode (does not echo back user input). The input is read to variable. These options s,p  are suitable for reading Password.

Example 1 – Read Password

In this example, we will write a Bash Shell Script to read username and password from console.

Bash Shell Script

#!/bin/bash

echo 'Welcome to TutorialKart'

read -p 'Username: ' username
read -sp 'Password: ' password

echo
echo "Thank you $username for showing interest in learning with www.tutorialkart.com"

## this echo is for demo purpose only, never echo password
echo "Your password is $password"

Note : An empty echo is provided after reading Password because read -sp  reads input in silent mode and does not echo back input including new line. However pressing enter key after password makes the input be loaded to password variable.

Output

$ ./bash-read-username-password Welcome to TutorialKart
Username: Arjun
Password: 
Thank you Arjun for showing interest in learning with www.tutorialkart.com
Your password is abc@1234

Example 2 – Read Password with *

In this example, we will read password from user with asterisk echoed back in the console/terminal.

Bash Shell Script

#!/bin/bash

unset username
unset password

# read username
read -p 'Username : ' username


echo -n "Enter password : "
stty -echo

#read password
charcount=0
while IFS= read -p "$prompt" -r -s -n 1 ch
do
    # Enter - accept password
    if [[ $ch ==

Output

arjun@arjun-VPCEH26EN:~/workspace/bash/readinput$ ./bash-read-username-password-2 
Username : Arjun
Enter password : ********
Thank you Arjun for showing interest in learning with www.tutorialkart.com
Your password is abc@1234

Recommended Reading : Bash Read User Input

Conclusion

In this Bash TutorialBash Read Password, we have learnt to read password without echoing back the password or masking it with some other characters.