Search code examples
for-loopshzshseparator

How to avoid using spaces as separators in zsh for-loop?


I'm trying to make a little script to convert some files from a music library.

But If I do something like :

#!/usr/bin/zsh                                                                     

for x in $(find -name "*.m4a");
do
    echo $x;
done

When interpreting in a folder containing :

foo\ bar.m4a

it will return :

foo
bar.m4a

How could I prevent the for loop from interpreting space characters as separators?

I could replace $(find -name "*.m4a") with $(find -name "*.m4a" | sed "s/ /_/g") and then using sed the other way inside the loop, but what if file names/paths already contain underscores (Or other characters I may use instead of underscore)?

Any idea?


Solution

  • Use zsh's globbing facilities here instead of find.

    for x in **/*.m4a; do
        echo "$x"
    done
    

    Quoting $x in the body of the loop is optional under the default settings of zsh, but it's not a bad idea to do so anyway.