Help with files and spaces with shell script

Cameron Simpson cs at zip.com.au
Mon Sep 17 00:40:54 UTC 2007


On 16Sep2007 20:21, Paul Ward <pnward at googlemail.com> wrote:
| > Enclose the names of the files with quotes. That has worked fine for me.
| 
| This does not work with loops unfortunately

it does and it doesn't. You need to understand when the shell is
breaking things up.

Example:
  
  find ... -print \
  | while read -r filename      # -r turns off some slosh interpretation
                                # that happens
    do
      mencoder ... "$filename" ...
      ls -ld *.mp3
    done

By enclosing $filename in double quotes you are telling the shell _not_
to look for word breaks there. The *.mp3 will reliably match filenames
with spaces in them, and preserve them, because the glob is expanded
_after_ the line is broken into words on whitespace.

For for loops, remember that the stuff after "in" is broken up just
like and other piece of shell.

So the counter-example:

  for mp3 in *.mp3

is perfectly safe with spaces in filenames.

On the other hand, using backticks to get the output of a command as
you are doing:

  for file in `find ...`

That is subject to space interpreation (it's outside quotes). But the
quoted version:

  for file in "`find ...`"

will bundle the find output into _one_ string. Also not what you want.

There are three common approaches:

  - fiddle $IFS to just contain a newline character, as suggested

  - write:
      find ... \
      | while read -r filename
    as I did earlier. The effect is much like the $IFS approach
    but without the $IFS fiddling.

  - use find's -exec option instead of -print:
      find ... -exec another-script.sh {} ';'

The last hands the filename off to another script of your choice where
the {} is. The shell is not involved in that and no word separation
occurs. other-script.sh gets the pure filename as $1.

Cheers,
-- 
Cameron Simpson <cs at zip.com.au> DoD#743
http://www.cskk.ezoshosting.com/cs/

(about SSSCA) I don't say this lightly. However, I really think that the U.S.
no longer is classifiable as a democracy, but rather as a plutocracy.
- H. Peter Anvin <hpa at hera.kernel.org>




More information about the fedora-list mailing list