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

后端 未结 11 1540
长情又很酷
长情又很酷 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:29

    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.

提交回复
热议问题