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

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

    BusyBox (used on embedded devices) is usually configured to support $RANDOM but it doesn't have bash-style arrays or sort --random-sort or shuf. Hence the following:

    #!/bin/sh
    FILES="/usr/bin/*"
    for f in $FILES; do  echo "$RANDOM $f" ; done | sort -n | head -n1 | cut -d' ' -f2-
    

    Note trailing "-" in cut -f2-; this is required to avoid truncating files that contain spaces (or whatever separator you want to use).

    It won't handle filenames with embedded newlines correctly.

提交回复
热议问题