Code Done Right!

Random Password Generator

This is a random password generator script for Bash. It generates a password with 1 special character, 1 number, 1 lowercase letter, 1 uppercase letter and 11-20 additional characters from a combination of numbers, lowercase and uppercase letters. Note that I excluded “0” zero, “i” and “l” to avoid confusion. If you are copy/pasting passwords you can add them again.

#!/bin/bash
choose() { echo ${1:RANDOM%${#1}:1} $RANDOM; }

{
    choose '!@#$%&'
    choose '123456789'
    choose 'abcdefghjkmnopqrstuvwxyz'
    choose 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    for i in $( seq 1 $(( 10 + RANDOM % 10 )) )
    do
        choose '123456789abcdefghjkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    done

} | sort -R | awk '{printf "%s",$1}'
echo ""

If you want to change the length of the password then modify the following line

for i in $( seq 1 $(( 10 + RANDOM % 10 )) 

First 10 is the fixed number of generated characters and the second 10 indicates a random number of additional characters, up to an additional 10 characters.

Note that some services have maximum lenght of passwords.

In order to generate a file with multiple passwords open terminal window in the folder with your script and run

while true; do ./pwd.sh >> pwd_list; done

If your script file is named pwd.sh the script will be executed indefinitely, or until you press Ctrl+C.

You will notice that it created a new file called pwd_list in the same folder. After a few seconds of running the script it will be filled with thousands of actually random passwords that you can use. Enjoy!

Creating an alias for ease of use

To make a permanent alias to the script check out this page. I have chosen passwd as the name for my alias.

If you just want to make a temporary alias to see how it works, use the following command. It will be retained in memory until you reboot.

alias passwd="/var/zzz_script/pwd.sh"

Now when you type passwd in your terminal the pwd.sh script will be executed and terminal will print a fresh password for you.

You can also make an alias that will create the file if you wish, however, since the need of a truly great number of passwords at once is rare you should not bother with that, unless you feel like you really want to.

In that case just use

alias pwdfile="while true; do /var/zzz_script/pwd.sh >> pwd_list; done"

After typing pwdfile the file with passwords will be created in the current directory.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.