Sometimes a Linux user can be in need of a random word generator. Random word can be used to set a new password or simply to create a bunch randomly named directories. If you need a single word the easiest way is to visit online Random Word Generator. However, if you need to generate more words or automate your task, a Linux bash shell can be a handy friend.
The following bash random word generator uses /usr/share/dict/words as word input ( feel free to use your own ). This file should be available on all decent Linux systems.
Here is how this random word generator works:
The random word generator script first gets a total number of words available in the /usr/share/dict/words file. Next, it will generate a random number in range from 0 to total number words available. As a last step, a previously randomly generated number will be used by a sed command to print a line corresponding with a random number generated previously.
Feel free to use your own words file by altering a constant variable ALL_NON_RANDOM_WORDS .
save a following bash script as random-word-generator:
#!/bin/bash # Random Word Generator # linuxconfig.org if [ $# -ne 1 ] then echo "Please specify how many random words would you like to generate !" 1>&2 echo "example: ./random-word-generator 3" 1>&2 echo "This will generate 3 random words" 1>&2 exit 0 fi # Constants X=0 ALL_NON_RANDOM_WORDS=/usr/share/dict/words # total number of non-random words available non_random_words=`cat $ALL_NON_RANDOM_WORDS | wc -l` # while loop to generate random words # number of random generated words depends on supplied argument while [ "$X" -lt "$1" ] do random_number=`od -N3 -An -i /dev/urandom | awk -v f=0 -v r="$non_random_words" '{printf "%i\n", f + r * $1 / 16777216}'` sed `echo $random_number`"q;d" $ALL_NON_RANDOM_WORDS let "X = X + 1" done
make random-word-generator script executable:
chmod +x random-word-generator
Execute random-word-generator script to generate 25 random words:
./random-word-generator 25