I am trying to print a random n
letter word, where I input n
from the command line itself, but for some reason my script is giving me the same answer every time when using the same value for n
.
#!/bin/bash
num=$1
egrep "^.{$num}$" /usr/share/dict/words | head -n $RANDOM| tail -n 1
I am calling my script like:
$ bash var3.sh 5
étude # always the same output when using 5
$ bash var3.sh 3
zoo # always the same output when using 3
where var3.sh
is the name of my script and 5 is the length of the word I want to print randomly.
How do I get it to print a truly random word?
$RANDOM
is pretty likely to be greater than the number of n-letter words for most values of n (95.7% of the time for n = 3 for me).shuf
orsort -R
as suggested in the answers. You can also use$RANDOM
, but in a more advanced way. All these tools produce results that can be predicted (they are not truly random), but they are fast and good enough for many purposes.