Bash Scripting Random Numbers

I needed to create a script that would pick a random line from a file.  The $RANDOM variable isn’t the easiest to use as it generates a psuedo random number between 0 – 32767 only.

The shuf command which I hadn’t heard of before makes this much easier.  To pick a random number between 0 and 5 you would use.

shuf -i 0-5 -n 1

The -i option selects the range and the -n is how many numbers to output.

To assign the contents of line number X in a file to a variable I used this code;

let RAND10k=`shuf -i 1-10000 -n 1`
MYVALUE=sed "${RAND10k}q;d" filename.txt

I assign the random number to a variable in the first line then use sed to get that line number from the file.

Be the first to comment

Leave a Reply

Your email address will not be published.


This site uses Akismet to reduce spam. Learn how your comment data is processed.