Skip to content

Instantly share code, notes, and snippets.

@consatan
Last active March 19, 2020 07:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save consatan/4a0f4dd2edb3f1321f94f49200249165 to your computer and use it in GitHub Desktop.
Save consatan/4a0f4dd2edb3f1321f94f49200249165 to your computer and use it in GitHub Desktop.
Generate random password
# Usage: rpasswd [LENGTH] [CHARS]
# Generate random password
#
# CHARS
# 'a': Alphabet, a-z A-Z
# 'n': Numeric, 0-9
# 'c': Character, print characters in ascii code
#
rpasswd() {
len=12
char='!-~'
if [[ $# -gt 0 ]]; then
if [[ "$1" =~ ^[0-9]+$ ]]; then
len=$1
fi;
if [[ $# -gt 1 ]]; then
nchar=""
for (( i=0; i<${#2}; i++ )); do
reg=""
case "${2:$i:1}" in
a | A)
reg='a-zA-Z';;
c | C)
reg='!-/:-@[-`{-~';;
n | N)
reg='0-9';;
esac;
nchar="${reg}${nchar}"
done;
if [ ! -z "$nchar" ]; then
char=$nchar
fi;
fi;
fi;
cat /dev/urandom | tr -dc $char | fold -w $len | head -n 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment