Last active
July 27, 2020 17:08
-
-
Save brnrs-pl/be6a1b6b1eabaede94b18695b95209cf to your computer and use it in GitHub Desktop.
Random Password Generator for Bash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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