1

For each file in a directory, I want to execute a python program.

#!/bin/bash

for file in mp3/* ; do
        if [[ "$file" == *.wav ]]; then
                python wav.py --file $file
        elif [[ "$file" == *mp3 ]]; then
                python mp3.py --file $file
        fi
done

How can I modify this bash script such that the files are taken in random order?

An approach may be to load the files from the directory (recursively) into a list and shuffle the list first. Sadly, I'm not too gifted in bash scripting.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Explicat
  • 1,075
  • 5
  • 16
  • 40

1 Answers1

1

Using sort -R will shuffle the list of files :

#!/bin/bash

ls mp3/* |sort -R |while read file; do

        if [[ "$file" == *.wav ]]; then
                python wav.py --file $file
        elif [[ "$file" == *mp3 ]]; then
                python mp3.py --file $file
        fi
done
Louise Miller
  • 3,069
  • 2
  • 12
  • 13
  • You have to use quotes around ``"$file"``, also [you always want to use -r flag with read](http://wiki.bash-hackers.org/commands/builtin/read#read_without_-r) and [parsing ls is bad](http://mywiki.wooledge.org/ParsingLs) – Aleks-Daniel Jakimenko-A. Jun 14 '14 at 14:08