Skip to content

Instantly share code, notes, and snippets.

@tobym
Last active August 29, 2015 14:08
Show Gist options
  • Save tobym/8592e5326a94ef53f1ce to your computer and use it in GitHub Desktop.
Save tobym/8592e5326a94ef53f1ce to your computer and use it in GitHub Desktop.
This script prints a random word to stdout.
#!/bin/bash
function print_random_word {
# The dictionary file. It contains one word per line.
dictionary=/usr/share/dict/words
# The number of words in the dictionary file.
num_words_in_dictionary=$(wc -l $dictionary | awk '{print $1}')
# A random number corresponding to a line in the dictionary file.
# This takes random data from /dev/random, converts it to an unsigned integer, and scales it by the number of words available.
random_line_number=$(($(cat /dev/random | od -N3 -An -D) % $num_words_in_dictionary))
# Prints the word corresponding to the random line calculated above.
awk "NR == $random_line_number" $dictionary
}
print_random_word
@tobym
Copy link
Author

tobym commented Oct 27, 2014

Along with mkString, this can implement the correct horse battery staple xkcd password generator:

#!/bin/sh

# Default the number of words in the passphrase to 4.
num_words=${1:-4}

# Get $num_words random words and string them together.
for n in $(seq $num_words); do randomword; done | mkString -

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment