Make Password

Here is a shell script that will create a function in your nix environment for generating complex passwords. The function is added to your shell by sourcing the script. For instance, you might store the script as ~/bin/mkpw.sh and source it from your .profile.

Your new password will start with an alpha character, include lowercase, uppercase, numeric, and special characters, and must be at least eight characters in length with a default of 16 characters in length. This has satisfied most systems I’ve encountered, the exception being when a less secure identity system does not allow special characters (who does that anymore?!?).

Call mkpw to invoke the command with the default password length of 16 characters. Call mkpw [integer] to create a password of a specified length (e.g., mkpw 12).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#!/bin/bash

display_usage() {
echo "Usage : . ~/bin/mkpw.sh"
}

# check script is sourced
if [[ $0 != "-bash" ]]; then
echo "Script must be sourced!"
echo ""
display_usage
exit 1
fi

function mkpw() {
# password will start with an alpha character
# password will include lowercase, uppercase, numeric, and special characters
# password must be at least 8 characters
# password length will default at 16 characters if no argument provided

local desiredLength
[ -z $1 ] && desiredLength=16 || desiredLength=$1

local re='^[0-9]+$'
if ! [[ $desiredLength =~ $re ]] ; then
echo "Error: argument must be an integer!"
return 1
fi

local minLength=8
if [[ $desiredLength -lt $minLength ]] ; then
echo "Error: passwords must be at least $minLength characters!"
return 1
fi

local uppercase='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
local lowercase='abcdefghijklmnopqrstuvwxyz'
local alpha=${uppercase}${lowercase}
local numbers='0123456789'
local symbols='!@#%^*()_-+='

local all=${uppercase}${lowercase}${numbers}${symbols}

local satisfied=0
local pw

while [ $satisfied -lt 4 ] ; do
local i=1
local uppercaseFlag=0
local lowercaseFlag=0
local numbersFlag=0
local symbolsFlag=0

local pos=0
let pos=($RANDOM % ${#alpha})+1
local chr=$(echo ${alpha} | cut -c${pos})
pw=${chr}

while [ $i -lt $desiredLength ] ; do
let i+=1
let pos=($RANDOM % ${#all})+1
chr=$(echo ${all} | cut -c${pos})
pw=${pw}${chr}
[[ $uppercase == *"${chr}"* ]] && uppercaseFlag=1
[[ $lowercase == *"${chr}"* ]] && lowercaseFlag=1
[[ $numbers == *"${chr}"* ]] && numbersFlag=1
[[ $symbols == *"${chr}"* ]] && symbolsFlag=1
done
let satisfied=$(expr $uppercaseFlag + $lowercaseFlag + $numbersFlag + $symbolsFlag)
done
echo $pw
}