I have a conv.sh script that loops over MP3 files in the current directory and converts them into OGG. I have also several directories {F1, F2,..., F20} at /path/to/Files/. How should I execute conv.sh on all of these directories?


Try this

for folder in /path/to/Files/*; do 
  [ -d "$folder" ] && cd "$folder" && ./conv.sh
cd $curdir

Or assuming you are at /path/to/Files/, this also works

for f in *; do [ -d "$f" ] && cd "$f" && ./conv.sh; done; cd ..

You could use F{1..20} instead of * for more precision.

  • Unfortunately, I get: 'bash: syntax error near unexpected token `do' – supermario Jan 31 '13 at 0:33
  • Woops, my bad, it's corrected now. There was an unneeded ; – Martín Canaval Jan 31 '13 at 1:57
  • 1
    Just needed replace '&& ./conv.sh' with of '&& bash /path/to/conv.sh'. Otherwise work as intended. Thanks – supermario Jan 31 '13 at 11:52
  • 1
    Either solution will break if your current working directory contains whitespace, you need to quote inside [, or use [[. – Chris Down Mar 11 '13 at 7:50

Try doing this :

./conv.sh /path/to/Files/F[0-9]*/*.mp3

This command treat only mp3 in dirs beginning with F and a number using globs


You can use xargs or GNU parallel:

echo /path/to/Files/F{1..20} | tr ' ' '\n' |
  xargs -L conv.sh


echo /path/to/Files/F{1..20} | tr ' ' '\n' |
  parallel conv.sh

Edit - handle space sensibly

As noted by Ole, none of the above methods handle space properly, i.e. dir name would be considered as two separate arguments, the same problem occurs if the directory name contains newlines.

The best way to handle these issues is to use null as delimiter, e.g. with GNU find:

find /path/to/Files -mindepth 1 -maxdepth 1 -type d -regex '.*/F[0-9]*' -print0 |
  parallel -0 conv.sh
  • 1
    This works with files containing space: parallel conv.sh ::: /path/to/Files/F{1..20} – Ole Tange Feb 4 '13 at 13:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.