How to Read Password in Bash [3 Practical Cases]

Taking a user password in Bash is an important task. One can utilize the read command to read passwords securely. Moreover, the openssl command provides the opportunity to encrypt passwords in an irreversible way. This article discusses three different cases of how to read a user password in Bash considering its security concern.

Key Takeaways

  • Reading password from user prompt.
  • Reading passwords securely using -s.
  • Securing passwords using hash encryption.

Free Downloads

3 Cases of Reading Password in Bash

The read command is commonly used to gather user input. Similarly, it’s handy for reading passwords while keeping them hidden with the -s option. Moreover one can read passwords from files. Let’s explore different scenarios of reading passwords in Bash.

Case 1: Reading Password from Prompt

The common approach to reading a password is by prompting the requirement of the password to the user. In the following script, I will show you how to read user password from the prompt using the read command.

Steps to Follow >

❶ At first, launch an Ubuntu Terminal.

❷ Write the following command to open a file named prompt.sh in the build-in nano editor:

nano prompt.sh
EXPLANATION
  • nano: Opens a file in the Nano text editor.
  • prompt.sh: Name of the file.
Creating a Bash script file in nano❸ Copy the following scripts and paste them into nano. Press CTRL+O and ENTER to save the file; CTRL+X to exit. Alternatively, copy the following script. Paste the script in a text editor and save it as .sh file.

Script (prompt.sh) >

#!/bin/bash

# Prompt the user for a password
read -p "Enter your password: " password
echo  # Move to a new line after reading the password

# Read the new username
read -p "Enter the username to add: " new_username
# Use sudo to add a new user
echo "$password" | sudo -S useradd "$new_username"

# Check if the user was added successfully
if [ $? -eq 0 ]; then
echo "User $new_username added successfully"
else
echo "Failed to add user $new_username"
fi
EXPLANATION

The script prompts the user to enter password using the read command. Then the user is prompted to provide a username for the new account. The script then employs the sudo command, along with the provided password, to add a user using the useradd command. Finally, it displays a confirmation message based on the exit status of the useradd command.

❹ Use the following two commands to make both file executable:

chmod u+x prompt.sh
EXPLANATION
  • chmod: Changes permissions.
  • u+x: Giving the owner executing permission.
  • prompt.sh: Name of the script.
Reading password without displayRun the prompt.sh script by the following command:
./prompt.sh

Read password from user promptThe image shows that the program first seeks the password of the user which is given as Ubuntu. Then it executes commands for adding a new user using the given password.

Case 2: Reading Password Without Displaying It to the User in Bash

The read command can be employed to capture a user’s password without displaying it on the screen. This approach adds an extra layer of protection and keeps passwords hidden from others’ sight. -s option of the read command is used for this purpose.

You can follow the Steps of Case 1 to learn about creating and saving shell scripts.

Script (hiddenpass.sh) >

#!/bin/bash
# Prompt the user for a password
read -p -s "Enter your password: " password
echo  # Move to a new line after reading the password

# Read the new username
read -p "Enter the username to add: " new_username

# Use sudo to add a new user
echo "$password" | sudo -S useradd "$new_username"

# Check if the user was added successfully
if [ $? -eq 0 ]; then
  echo "User $new_username added successfully"
else
  echo "Failed to add user $new_username"
fi
EXPLANATION

The script prompts the user to input password using the -s flag, ensuring the password remains unrevealed on the screen. Subsequently, the script prompts for a username. The provided password is then used to execute the sudo -S useradd command, adding the new user with the specified username. Finally, it displays a confirmation message based on the exit status of the useradd command whether the new user is created successfully or not.

Run the hiddenpass.sh script by the following command:

./hiddenpass.sh

Changing permission of Bash script fileYou can see user Bin is created successfully after reading the system password from the current user. However, the given password is not displayed while reading it from the user. The  -s option of read command successfully hides the password.

NOTE: You can achieve a similar effect using the stty command. It can control terminal settings and hide user input from the terminal. For example, stty -echo will hide user input while using read command.

Case 3: Reading Password from a Password File

Imagine having a password file where you’ve stored all your passwords. Instead of inputting the password manually through a prompt, a program can retrieve it directly from the saved file. Let’s see how it works.

You can follow the Steps of Case 1 to learn about creating and saving shell scripts.

Script (filepass.sh) >

#!/bin/bash

file="password.txt"
# Use 'grep' to find the password
password=$(grep "Linux :" "$file" | awk -F ': ' '{print $2}')

# Check if the password was found
if [ -z "$password" ]; then
echo "Password not found."
exit 1
else
echo "System successfully finds the password."
fi

# Read the new username
read -p "Enter the username to add: " new_username
# Use sudo to add a new user with the extracted password
echo "$password" | sudo -S useradd "$new_username"

# Check if the user was added successfully
if [ $? -eq 0 ]; then
echo "User $new_username added successfully"
else
echo "Failed to add user $new_username"
fi
EXPLANATION

This Bash script reads the content of password.txt file and attempts to find a password associated with Linux. It uses the grep command to search for a line containing “Linux :” and then employs awk to extract the password field following the colon.

The script utilizes the extracted password as input to the sudo -S useradd command, attempting to add a new user with the specified username using the extracted password.

After the user addition attempt, the script checks the exit status of the useradd command. If the exit status is 0, it prints a success message indicating that the user was added; otherwise, it prints a failure message.

Now see the password.txt file first using the command below:

cat password.txt

File with passwordAs you can see there are passwords for various applications stored in the password.txt file. The password for Linux is in the third line of the file.

This time run the filepass.sh script by the following command:

./filepass.sh

Reading password from fileAs you can see the program reads the password of Linux from the file. Using this password it successfully added a new user Jemmy to the system.

Echoing * (Asterisk) for Each Character while Reading Password

Someone may be confused whether a program takes password or not if nothing is displayed on the terminal. So, instead of displaying nothing one can use the following script to display an asterisk for each inputted character of the password.

You can follow the Steps of Case 1 to learn about creating and saving shell scripts.

Script (asterisk.sh) >

#!/bin/bash

password=""
prompt="Enter your password: "

while IFS= read -p "$prompt" -r -s -n 1 letter; do
if [[ $letter == $'\0' ]]; then
break
fi
password="$password$letter"
prompt="*"
done

echo -e "\nPassword entered: $password"
EXPLANATION

The script initializes an empty password variable and seeks the password from the user. Then it enters in a while loop where the read command is used to capture individual characters of user input.

-r -s -n 1 ensures that the input is read silently by avoiding backslashes and reading only a single character at a time. An asterisk is displayed for each appended character to the password variable.

Run the asterisk.sh script by the following command:

./asterisk.sh

Echoing asterisk while taking passwordAs evident, the script displays asterisks to validate each user input. In this instance, the user entered Ubuntu as the password, resulting in the display of six asterisks. This pattern confirms to the user that their input has been accurately captured.

How to Encrypt Password Using Hash Algorithm in Bash

One can encrypt password using openssl command for public servers. It uses various hash algorithms such as SHA-256 algorithm and a randomly generated salt to encrypt a password. Hashing is a one-way function. It means that once a password is hashed, it isn’t easy to convert it back to the original.

You can follow the Steps of Case 1 to learn about creating and saving shell scripts.

Script (encryption.sh) >

#!/bin/bash

# Generate a random salt
salt=$(openssl rand -base64 8)

# Get the password from the user
read -p "Enter your password: " password

# Combine the password and salt, then hash using SHA-256
hashed_password=$(echo -n "$password$salt" | openssl dgst -sha256 -binary | base64)

echo "Salt: $salt"
echo "Hashed Password: $hashed_password"
EXPLANATION

In this Bash script a random 8-byte salt is generated using the openssl command. The user is prompted to input a password. The script then combines the user’s password and the generated salt.

This concatenated string is hashed using the SHA-256 algorithm through the openssl dgst command. The resulting binary hash is then encoded in base64 format to generate the final hashed password.

Run the encryption.sh script by the following command:

./encryption.sh

Encrypt password using a hash algorithms in bashHere the password Ubuntu is hashed using openssl command. The encrypted password is displayed in the image above.

Conclusion

In conclusion, one can read a user password in Bash in various ways with different layers of protection. Moreover, one can store encrypted passwords using hash-based algorithms. I believe from now on you can take user password securely as well as encrypt password where necessary.

People Also Ask

How to save password into environment variable?
Use the export command to save password in any of the environment variable. 
Does -s option of read command is used to take input in a new line?
No. -s option of read command is used to take input securely without displaying it to the terminal. To take user input in a new line use -n option not -s.
Why do you need to read user password in Bash?
User password is needed for various actions in Bash. For example, if you want to install new packages or add new users via the sudo command then reading user passwords becomes essential for granting root privileges.

Related Articles


<< Go Back to Bash Script Examples | Bash Scripting Basics | Bash Scripting Tutorial

Rate this post
Md Zahidul Islam Laku

Hey, I'm Zahidul Islam Laku currently working as a Linux Content Developer Executive at SOFTEKO. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). I write articles on a variety of tech topics including Linux. Learning and writing on Linux is nothing but fun as it gives me more power on my machine. What can be more efficient than interacting with the Operating System without Graphical User Interface! Read Full Bio

Leave a Comment