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

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

    # ******************************************************************
    # ******************************************************************
    function randomFile {
      tmpFile=$(mktemp)
    
      files=$(find . -type f > $tmpFile)
      total=$(cat "$tmpFile"|wc -l)
      randomNumber=$(($RANDOM%$total))
    
      i=0
      while read line;  do
        if [ "$i" -eq "$randomNumber" ];then
          # Do stuff with file
          amarok $line
          break
        fi
        i=$[$i+1]
      done < $tmpFile
      rm $tmpFile
    }
    

提交回复
热议问题