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

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

    Newlines in file-names can be avoided by doing the following in Bash:

    #!/bin/sh
    
    OLDIFS=$IFS
    IFS=$(echo -en "\n\b")
    
    DIR="/home/user"
    
    for file in $(ls -1 $DIR)
    do
        echo $file
    done
    
    IFS=$OLDIFS
    

提交回复
热议问题