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

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

    Is "shuf" not portable?

    shuf -n1 -e /path/to/files/*
    

    or find if files are deeper than one directory:

    find /path/to/files/ -type f | shuf -n1
    

    it's part of coreutils but you'll need 6.4 or newer to get it... so RH/CentOS does not include it.

提交回复
热议问题