Generating strong passwords is a fundamental practice for protecting sensitive information. An interactive Bash script can be a great tool for generating random passwords, configurable to the user's needs. In this article, we will explore step by step how to create a Bash script that allows you to generate random passwords of different lengths and complexity, interacting with the user to customize the options.
Our goal is to create a script that:
- Allows the user to specify the length the password should be.
- Allows you to choose whether or not to have special characters in the generated password.
#!/bin/bash
# Ask for password length
read -p "Enter the desired password length: " PASSWORD_LENGTH
# Ask whether to include special characters
read -p "Do you want to include special characters? (y/n): " INCLUDE_SPECIALS
# Determines the character set to use
if [[ $INCLUDE_SPECIALS == "y" || $INCLUDE_SPECIALS == "S" ]]; then
CHAR_SET='A-Za-z0-9!@#$%^&*()+='
else
CHAR_SET='A-Za-z0-9'
fi
# Function to generate the password
generate_password() {
local LENGTH=$1
local CHAR_SET=$2
tr -dc "$CHAR_SET" </dev/urandom | head -c $LENGTH
echo
}
# Generate password
echo "Generating password..."
PASSWORD=$(generate_password $PASSWORD_LENGTH $CHAR_SET)
echo "Your generated password is: $PASSWORD"
To make the script even more versatile, you can add options such as:
- The ability to generate multiple passwords at once.
- Support for different levels of complexity (e.g., numbers only, uppercase letters, etc.).
- Saving the generated password to a file.
Conclusion
Creating an interactive Bash script to generate random passwords is a great exercise in learning how to use the scripting language and improve your personal cybersecurity. This script can be further extended to include more advanced features or integrated into other security management tools.