1

Since ls returns the files in alphabetical order, is there a way to return the same files but in a random order? I am trying to loop through all the files in a directory, but would like it to differ in separate runs.

for i in *.py # Would like order to be random
do
    ...
done
Nole
  • 119
  • 1
  • 3
  • 14

1 Answers1

5

This is a duplicate of randomly shuffling files in bash and How can I shuffle the lines of a text file on the Unix command line or in a shell script?

However, this should do the job:

for i in `ls *.py | shuf`
do
    echo $i
done
Xaraxia
  • 199
  • 9
  • Be aware, this will error if there are no python files in the folder. – Xaraxia Aug 17 '18 at 06:22
  • 1
    This is similar but it will succeed even if there are filenames with `\n` ... `find . -name \*.py -print0 | shuf -z | xargs -0 -L 1 sh -c 'for i ; do printf "%s\n" "${i}" ; done' notusebutmandatory` – Jay jargot Aug 17 '18 at 06:50