Bash script password generator

This is a simple Bash script I wrote to generate random passwords.

#!/usr/bin/bash
#
# passwordGenerator.sh
#
#-------------------------------------------------------------------------------
# *** DEFAULTS ***
#allowedChars='1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%()[]{}.,:;_+*-/'
allowedChars='1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz$!#%'
length=12
num=1
#-------------------------------------------------------------------------------

while getopts ":a:l:n:" opt
do
	case $opt in
		a)
			allowedChars=$OPTARG
		;;
		l)
			length=$OPTARG
		;;
		n)
			num=$OPTARG
		;;
		\?|:)
			echo "Usage: "`basename $0`" [ -a \"string\"] [ -l lenght ] [ -n iterations ]"
			echo " -a: Allowed characters for password"
			echo " -l: Password length"
			echo " -n: Number of passwords to generate"
			echo ""
			echo " Example: "`basename $0`" -a '12345ABCDabcd#!$' -l 10 -n 3"
			echo ""
			echo " Default values"
			echo " ---------------"
			echo " Allowed characters:  $allowedChars"
			echo " Password length:     $length"
			echo " Number of passwords: $num"
			exit 0
		;;
	esac
done


for (( i = 1 ; i <= num ; i++ ))
do
	tr -dc "$allowedChars" < /dev/urandom | head -c$length ; echo ""
done

exit 0

#EOF#

The script accepts 3 switches
-a: Allowed characters for password
-l: Password length
-n: Number of passwords to generate

By default, it prints one password of length defined by $length, using the characters defined in $allowedChars string.

$ passwordGenerator.sh
Mq!XhwwBX$4O

To print, for example, 3 password:

$ passwordGenerator.sh -n 3
LS6erpzo1xYI
d7aALnFF%DEq
d7bJEvoi2ITI

To print 3 password of 30 characters length, using a ABCD1234 as set of characters:

$ passwordGenerator.sh -n 3 -l 30 -a 'ABCD1234'
A3BABAABDB1D2CDA3A32C333DB2444
BBC1CC2344A331B3CA2B144C2DC3C3
C2C3ADB13A432243B2BD1DCCBDC222

Leave a Reply