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

后端 未结 11 1587
长情又很酷
长情又很酷 2020-12-13 02:00

What is the best way to choose a random file from a directory in a shell script?

Here is my solution in Bash but I would be very interested for a more portable (non-

11条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-13 02:14

    My 2 cents, with a version that should not break when filenames with special chars exist:

    #!/bin/bash --
    dir='some/directory'
    
    let number_of_files=$(find "${dir}" -type f -print0 | grep -zc .)
    let rand_index=$((1+(RANDOM % number_of_files)))
    
    printf "the randomly-selected file is: "
    find "${dir}" -type f -print0 | head -z -n "${rand_index}" | tail -z -n 1
    printf "\n"
    

提交回复
热议问题