Best way to choose a random file from a directory in a shell script

files=(/my/dir/*)
printf "%s\n" "${files[RANDOM % ${#files[@]}]}"

And don’t parse ls. Read http://mywiki.wooledge.org/ParsingLs

Edit: Good luck finding a non-bash solution that’s reliable. Most will break for certain types of filenames, such as filenames with spaces or newlines or dashes (it’s pretty much impossible in pure sh). To do it right without bash, you’d need to fully migrate to awk/perl/python/… without piping that output for further processing or such.

Leave a Comment