Randomize Your Music with MPD and mpc

I use MPD (Music Player Daemon) on a Raspberry Pi to manage my music playback. I've mostly been using Cantata as a GUI client that allows me to drag and drop tracks or albums onto the play list, but I decided it was time to explore mpc - a command line client for MPD. mpc is everything good and bad about Linux and Unix: it's old and powerful, and because of these things, it's complex and takes some time to learn.

My new best friend is the command shuf, which I only just found out about. I think it's actually fairly new? (You know - NOT 40 years old like most Unix utilities.) I wanted to randomize tracks from my music collection, and feed them back into MPD in manageable chunks. I thought I would have to read the output of mpc listall into a Bash array, generate random numbers, pull elements of the array ... But it's way, way easier than that with shuf:

# how many songs to add:
nopicks=10
# when the queue is shorter than this value:
minqueue=10

if [ "$(mpc playlist | wc -l)" -le "${minqueue}" ]
then
    mpc listall | shuf -n ${nopicks} | mpc add
else
    echo "queue to long, not adding songs."
fi

Seriously: that's it. It's only that long because I got fancy and checked that I wasn't adding to an already-long queue first, and printed output when I don't add tracks. The reason I do this is because I often enqueue whole albums in Cantata - and one of the beauties of MPD is you can mix and match both of these behaviours without problems.

shuf is described as "Write a random permutation of the input lines to standard output." We feed it in excess of 10,000 lines (my music collection) and it spits out ten at random, which we immediately feed back into mpc as additions to the MPD playlist.

The thought is to run this script on a cron job every ten minutes or so, so it will only add new tracks to the queue when the queue is running low. Another way of handling this would be to increase the queue length to a set count rather than adding a set number of tracks each time. The only thing I don't like about this arrangement is that I have to have "consume" turned on (each track is removed from the queue after it's played - otherwise the queue doesn't get shorter). What if I didn't know what that last track was (it's a big music collection)? I can't look at the queue to find out ... I'll see if I can find a solution to that.