Pick a random file from a directory

AKA. Which movie should I watch today?

Unfortunately the version of sort shipped with Mac OS doesn't include the -R / --random-sort option and shuf doesn't come by default. We'll have to install GNU's coreutils to use them.

If you are using homebrew it's as simple as running brew install coreutils. Once installed it's available via gsort. All the GNU coreutils are prefixed with g so they are not conflicting with the system provided tools.

ls Movies/ | gshuf -n 1

It's also possible to be used with find if you need more flexibility (Only want it to choose between all 720p *.mkv files? No problem!

find Movies/*.mkv -name "*720p*" -type f | gshuf -n 1

And because I'm lazy I wrote a little shell script* with suggests a random movie based on some input parameters.

And this is how it works:

Movies|⇒ popcorntime -p ~/Movies -e mkv -q 720p
You should watch:

If you want to call it with popcorntime instead of ./popcorntime.sh you'll have to add an alias to your ~/.zshrc like that:

alias popcorntime="sh ~/path/to/popcorntime.sh"

Make sure the script is executable with:
chmod +x ~/path/to/popcorntime.sh

The End.

*As usual writing a quick zsh function turned into a shell script and that task turned into a 2h BashFAQ binge.

Relevant XKCD:

Pick a random file from a directory
Share this