I have a script I made to play random media files I have stored in various locations. In determining which file to play, first I do an ls of all the directories and append the outputs to file.txt. Then, in order to select a random line from the file (which = one media file), I'm using this bit of code I found somewhere online:
Code:
LowerBound=1
RandomMax=32761
UpperBound=$(cat $file.txt | wc -l)
RandomLine=$(( $LowerBound + ($UpperBound * $RANDOM) / ($RandomMax + 1) ))
filetoplay=$(sed -n "$RandomLine{p;q;}" "$file.txt")
The randomness of this setup is pretty questionable. Out of over 500 media files, I seem to be stuck with the same 30 or 40 over and over. Even when I play in batches using a while/do loop and counting cycles to a predetermined number, I can end up with duplicate plays of media files. I believe it's because the $RANDOM variable works between 0-32761, and that math up there isn't enough to sufficiently scale it down to a few hundred.
Some more searching has led me to the fact that $RANDOM can be limited, by using $RANDOM%NN, where NN is a limiting number of your choice. Since it runs from zero to (NN-1), you have to add one to the equation such that (( [ $RANDOM%NN ] +1 )). I'd like to do away completely with much of the previous setup, and cut that process down a lot by, for example, renaming the "UpperBound" variable "max" and using it to limit the $RANDOM output as shown above. The problem is that I keep getting errors or strange outputs when I try to insert a variable into that setup. For example, (( [ $RANDOM%$MAX ] +1 )) just gives a syntax error. Using it like (( [ $RANDOM%${MAX} ] +1 )) gives a count from 0 to 2, with each digit followed by the actual value for the $max variable.
Can someone point me in a direction (either this one or something totally new) that will allow me to limit the output of the $RANDOM variable with the use of a second variable?