Open In App

Bash Scripting – Bash Read Password without Echoing back

Last Updated : 28 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Generally, you can see on the login page, whenever we type a password either it show dot (•) or asterisk (*) instead of a password. They do so because to protect our system or account. In such a case, the login page read the password and in place of the password, it will show a dot or asterisk. And in some cases, a dot or asterisk also may not appear it means it displays nothing in place of a password.

Let see how to read the password without echoing back

First, create a file named ” User.sh ” using the following command

$ touch User.sh

Now open ” User.sh ” in the text editor 

$ nano User.sh

Now write the below bash script into ” User.sh “

#!/bin/bash
echo "Enter Username : "

# read username and echo username in terminal
read username
echo "Enter Password : "

# password is read in silent mode i.e. it will
# show nothing instead of password.
read -s password 
echo
echo "Your password is read in silent mode." 

Note: Here ‘ -s ‘ is used to read passwords because it will read passwords in silent mode

Now save the above bash script and run ” User.sh ” by following the command

$ chmod +x ./User.sh
$ ./User.sh

Output : 

It read password and show nothing there

Here, we can see clearly that the above script will read username as well as password but it does not echo the password.

Let see how to read the password with ” * “

Now, create a file named ” Password.sh ” using the following command

$ touch Password.sh

Now, open ” Password.sh ” in the text editor

$ nano Password.sh

Now write below bash script into ” Password.sh “

#!/bin/bash

password=""
echo "Enter Username : "

# it will read username
read username
pass_var="Enter Password :"

# this will take password letter by letter
while IFS= read -p "$pass_var" -r -s -n 1 letter
do
    # if you press enter then the condition 
    # is true and it exit the loop
    if [[ $letter == $'\0' ]]
    then
        break
    fi
    
    # the letter will store in password variable
    password=password+"$letter"
    
    # in place of password the asterisk (*) 
    # will printed
    pass_var="*"
done
echo
echo "Your password is read with asterisk (*)."

Note: Here,

  • IFS: It is Internal Field Separator used to split words or characters
  • -r: It will read the password.
  • -p: It will echo input character by character.
  • -s: It will read the password in silent mode.
  • -n: It does not print the trailing newline. 

Now save the above bash script and run ” Password.sh ” by the following command

$ chmod +x ./Password.sh
$ ./Password.sh

Output : 

Output: Read password with an asterisk (*)

Here, we can see clearly that the above script will read username as well as password with an asterisk (*)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads