Posts Tagged ‘random’

Selecting a random file/folder of a folder in Linux

I always had the following problem: “How to select which movie (from the ones in my collection) to watch“. In the past, I had used the random (pseudo-random to be precise) capabilities of C, Java, Erlang, and Javascript to select the movie.

Today I wrote a simple script that selects a random content (file or folder) within a folder:

#! /bin/sh
 
if [ $# -gt 0 ]; then
    cd "$1";
fi
 
ls -1 | awk 'BEGIN {srand()}
	{x[NR] = $0}
	END {print "Selected", x[1 + int(rand() * NR)]}'

Save it in a file (lets say srandom, make it executable:

$ chmod +x srandom

and execute it either with 0 or 1 arguments. Without an argument, the selection is done from the contents of the srandom‘s container, else the path given as an argument is used.

$ ./srandom.sh
Selected lrandom.html
$ ./srandom.sh /bin
Selected gzexe

Update

A much more elegant solution:

$ ls -1 | shuf -n1