Rowland Carlson

How to print a random filename from a directory

2022-07-15

This script outputs the filename of a random file:

#! /usr/bin/env bash
DIRECTORY_FILES=$(find $1 -not -type d)
FILE_COUNT=$(echo "$DIRECTORY_FILES" | wc -l)
RANDOM_INDEX=$(($RANDOM % "$FILE_COUNT" + 1))
echo "$DIRECTORY_FILES" | head -"$RANDOM_INDEX" | tail -1

Note the double (( around the code for RANDOM_INDEX.
That is a bash-ism that allows for math calculations.