Get a random file from a directory with the Linux terminal


2014-01-12

Here's how you can grab a random file from a directory using the GNU/Linux terminal:

ls | shuf -n 1

And perhaps you want to do something like open that file with a program:

your_program `ls | shuf -n 1`

I used this to do things like open a random image with feh from my pictures folder:

cd Pictures; feh `ls | shuf -n 1`

The magic here is the shuf command that will output n pseudorandom items from a collection that is fed to it.