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
  • 107,083
  • 22
  • 201
  • 376
Explicat
  • 1,047
  • 5
  • 15
  • 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
  • 2,799
  • 2
  • 11
  • 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