Skip to content

Instantly share code, notes, and snippets.

@brnrs-pl
Last active July 27, 2020 17: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 brnrs-pl/be6a1b6b1eabaede94b18695b95209cf to your computer and use it in GitHub Desktop.
Save brnrs-pl/be6a1b6b1eabaede94b18695b95209cf to your computer and use it in GitHub Desktop.
Random Password Generator for Bash
#!/bin/bash
# thanks to StackOverflow: https://stackoverflow.com/questions/101362/how-do-you-generate-passwords
while [ -n "$1" ]; do
case "$1" in
'-n')
PASSWORD_LENGTH="$2"
shift
;;
'-p')
PUNCTUATION_OPT='[:punct:]'
;;
'-h')
cat <<END
rpg.sh: Random Password Generator for bash!
usage:
-n <num> specify length of password
-p enable punctuation characters in generated password
-h print this
END
exit 0
;;
*)
echo "Unrecognized option $1" 1>&2
exit 1
;;
esac
shift
done
if [ -z "$PASSWORD_LENGTH" ]
then
PASSWORD_LENGTH='12'
elif ! [[ $PASSWORD_LENGTH =~ ^[1-9][0-9]*$ ]]
then
echo "Invalid length: $PASSWORD_LENGTH" 1>&2
exit 1
fi
# Explanation:
# 1. use cat to read random bytes from /dev/urandom
# 2. use tr to filter so as to only include alphanumeric (optionally, also punctuation) characters
# 3. use fold to split the stream into lines of the given length
# 4. use head to only print the first line
cat /dev/urandom | tr -dc "[:alnum:]${PUNCTUATION_OPT}" | fold -w "$PASSWORD_LENGTH" | head -n 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment