Last active
June 29, 2016 14:50
-
-
Save jeremytwfortune/7c8de642ffa1f02575931a08b23535f4 to your computer and use it in GitHub Desktop.
Random
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 | |
# random | |
# Creates random strings based on urandom. | |
usage() { | |
echo "$(basename $0)" | |
echo ' Returns random strings based on the subcommand.' | |
echo ' The seed subcommand defauls to length 40; all others are 20.' | |
echo "Usage: $(basename $0) (seed|number|name|word) [-l | --length] <length>" | |
} | |
# Subcommand. | |
case "$1" in | |
seed) | |
re='[[:graph:]]' | |
length=40 | |
shift | |
;; | |
number) | |
re='0-9' | |
numeric=true | |
shift | |
;; | |
name) | |
re='a-z0-9' | |
shift | |
;; | |
word) | |
re='a-z' | |
shift | |
;; | |
*) | |
usage | |
exit 2 | |
;; | |
esac | |
# Optional args. | |
args=$(getopt -o l: -l "length:" -n "$(basename $0)" -- "$@") | |
if [[ $? -ne 0 ]]; then | |
echo "$(basename $0): invalid argument" >&2 | |
exit 2 | |
fi | |
eval set -- "${args[@]}" | |
while true; do | |
case "$1" in | |
-l|--length) | |
length=$2 | |
shift 2 | |
;; | |
--) | |
shift 1 | |
break | |
;; | |
*) | |
usage | |
exit 2 | |
;; | |
esac | |
done | |
# Defaults. | |
if [[ -z $length ]]; then | |
length=20 | |
fi | |
if [[ -z $numeric ]]; then | |
numeric=false | |
fi | |
if $numeric; then | |
rand=$(< /dev/urandom tr -dc "$re" | fold -w $length | head -1) | |
else | |
prefix=$(< /dev/urandom tr -dc 'a-z' | fold -w 1 | head -1) | |
suffix=$(< /dev/urandom tr -dc "$re" | fold -w $(( length - 1)) | head -1) | |
rand="$prefix$suffix" | |
fi | |
echo "$rand" | |
if [[ $(uname) == 'CYGWIN'* ]]; then | |
putclip <<< "$rand" | |
fi | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment