[buug] Spaces within filenames in a bash script

Michael Paoli Michael.Paoli at cal.berkeley.edu
Mon Jan 9 01:23:58 PST 2006

Quoting Joseph Zitt:

> tweaked to do oggs, but the problem would be the same.) It's blowing up
> badly on files with spaces in the names:
> #!/bin/bash
> FILES=$(ls *.flac | cut -d '.' -f1)
> for i in $FILES; do
>          echo converting: $i.flac
>          flac -sdc $i.flac | lame - $i.mp3
> done

You could try something roughly like:
unset ret
for flac in *.flac
    if [ -f "$flac" ]; then
        #exists as ordinary file (or symlink to ordinary file)
        echo "$0: converting: $flac"
        b="`basename "$flac" .flac`"
        flac -sdc -- "$flac" | lame - -- "$b".mp3 && ret="${ret-0}"
        if [ X'*.flac' != X"$flac" ] || >>/dev/null 2>&1 ls -d "$flac"; then
            #not an ordinary file
            1>&2 echo "$0: skipping $flac: not a file"
exit "$ret"

I also made some presumptions about flac and lame taking -- to indicate
end of all options - this tends to be generally true with most newer
UNIX/LINUX commands, but isn't necessarily supported on all commands.

Carefully study the man page stuff (e.g. bash(1) or sh(1)), paying
particular attention to various forms of quoting and command
substitution (and how they also interact).

Lots of stuff stuck in articles, web sites, etc., are probably more
often meant for or more useful for general illustrative examples, rather
than particularly robust and complete code examples (this is often
particularly the case in print when space may be at a premium).  Of
course lots of folks also write less than wonderfully robust code.

The example bit I did, above, is also just for illustrative purposes
:-).  It certainly makes some improvements, but it doesn't handle
everything ideally, e.g. ideally if flac failed (e.g. exited non-zero)
that should cause the script to return a non-zero value when it


More information about the buug mailing list