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 9-16 additional characters from a combination of numbers, lowercase and uppercase letters. Note that I excluded “0” zero, “i” and “l” to avoid confusion.

#!/bin/bash

if  [[ $1 = -m ]]; then
	for i in `seq $2`;
	do
		choose() { echo ${1:RANDOM%${#1}:1} $RANDOM; }

		{
    		choose '!@#$%&'
    		choose '0123456789'
    		choose 'abcdefghijklmnopqrstuvwxyz'
    		choose 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    		for i in $( seq 1 $(( 8 + RANDOM % 8 )) )
    		do
        		choose '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    		done

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

choose() { echo ${1:RANDOM%${#1}:1} $RANDOM; }

{
    choose '!@#$%&'
    choose '0123456789'
    choose 'abcdefghijklmnopqrstuvwxyz'
    choose 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    for i in $( seq 1 $(( 8 + RANDOM % 8 )) )
    do
        choose '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    done

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

fi

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

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

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

In order to generate multiple passwords, run the script with -m # option, where # is the number of passwords that you want to generate. Like so

./foo.sh -m X

In order to save generated passwords to a file, redirect output of the script like so

./foo.sh -m X > file.txt

This will create a file named file.txt that will contain your fresh passwords.

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.