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.

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 the user password from the prompt using the read command.

To read a password by prompting to the user, please see the following bash script:

#!/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 the 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.

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. The -s option of the read command is used for this purpose.

To read a password in a hidden manner, use the Bash script below:

#!/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 a 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.

Changing permission of Bash script fileYou can see that the 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 the 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 the 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.

To read a password from a password file, please go through the below script:

#!/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 the 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.

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.

Reading password from fileSee the output image, 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 a 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:

#!/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.

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

You can encrypt passwords using the openssl command for public servers. It uses various hash algorithms such as the 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.

To encrypt passwords using the hash algorithm in bash, see the below script:

#!/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.

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 passwords securely as well as encrypt passwords where necessary.

People Also Ask

How to read in bash script?

To read user input in the Bash script, you can simply use the read command. It takes input from the user and assigns it to the variable. You can also use the -p option of the read command to provide a prompt to the user directly.

How to save password into environment variable?

To save the password in any of the environment variables use the export command. For that, use the syntax, export MY_PASSWORD="your_password_here".

Does -s option of read command is used to take input in a new line?

No. The -s option of the 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?

Reading user passwords 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
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
icon linux
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