Well, you can do it in three parts:
- collect all filenames from path in temporary array;
- loop once for each random filename desired, choose random element from temp array;
- output selected filenames
In bash, that would look like:
#!/bin/bash
oifs="$IFS" ## save original Internal Field Separator
IFS=$'\n'; ## set IFS to \n to accommodate spaces in filenames
a=($(find /path/to/files -type f)) ## temporary array holding all filenames
IFS="$oifs" ## restore original IFS
n=${#a[@]} ## number of files in array
for ((i=0; i<3; i++)); do ## loop over number of random files desired
b[$i]=${a[$((RANDOM % n))]} ## choose random element from temp array
done
for ((i=0; i<3; i++)); do ## loop again outputting chosen files
echo "${b[i]}"
done
Now obviously for purpose of the example I have hardcoded 3
as the number of random filenames to choose, you can handle that any way you like, you should add a check that ((n > 0))
before using it with $((RANDOM % n))
, and you can unset
the temporary array if you like -- those are left to you.
If you have hundreds of thousands of files or millions of files, you way use a temp file instead of array and then use sed
to pick a random line from the file.
Look things over and let me know if you have any questions.