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?
Best Answer
It doesn't. But $RANDOM returns big numbers (between 0 and 32767) which, especially for words of limited lengths, shows the same result, as the
head
portion probably returns all the results of the grep (for 3, there are only 819 matches in my/usr/share/dict/words
).Better solution might be to shuffle the results:
egrep "^.{$num}$" /usr/share/dict/words | sort -R | tail -n 1
where
-R
means--random-sort
(a GNUsort
extension).