Table of Contents
On Linux, run shuf -n 1 /usr/share/dict/words to pick one random line from the system word list. If that file is missing, make a text file with one word per line and pass its path to the command. Each call makes a new draw and can repeat a previous word.
Make or choose a word list
The system dictionary is optional and its path can vary by distribution. For a quick test, save these lines as words.txt in your current directory.
apple
cedar
harborRun shuf -n 1 -- words.txt. The -n 1 option limits output to one line. It samples lines, so duplicates in the file give that word more chances to appear. See the GNU Coreutils reference.
Save a reusable Bash script
Save the following as random-word.sh. Pass a path to use your own list. Otherwise it checks the standard dictionary path. The script drops lines containing only whitespace and reports an error when there’s nothing to pick.
#!/usr/bin/env bash
set -o pipefail
word_file=${1:-/usr/share/dict/words}
if ! command -v shuf >/dev/null 2>&1; then
printf '%sn' 'GNU shuf is required.' >&2
exit 1
fi
if [[ ! -f "$word_file" || ! -r "$word_file" ]]; then
printf 'Cannot read word list: %sn' "$word_file" >&2
exit 1
fi
if ! word=$(awk 'NF { sub(/r$/, ""); print }' < "$word_file" | shuf -n 1); then
printf '%sn' 'Could not sample the word list.' >&2
exit 1
fi
if [[ -z "$word" ]]; then
printf '%sn' 'The word list has no nonblank lines.' >&2
exit 1
fi
printf '%sn' "$word"
Run bash random-word.sh words.txt. The script prints one word to standard output, which makes it easy to use in another script. For example, you might choose a word for a game or generate sample data. Use a password manager’s generator for real passwords. A single dictionary word is easy to guess.
For more practice, see how to work with shell pipelines or the full command line and shell course.
Reader Comments 0
Sign in with email or Google to join the discussion.