[svlug] Working with spaces in shell scripts

William R Ward bill at wards.net
Tue Dec 14 15:48:01 PST 2004

Nathan writes:
>I want to remove the some files from inside a bunch of directories with
>spaces in the names. But when my script hits a directory with a space in
>its name the script will treat it as two separate directories (ie
>"Monkey Joe" becomes "Monkey" and "Joe"). Can this even be done with a
>shell script? Should I break down and use perl? 

You have to either have quotes around the filename or put a backslash
in front of the space.  I've found this to be pretty annoying so I
don't generally use spaces in file or directory names as a result.

These should all work:

rm "Monkey Joe"/*
rm 'Monkey Joe'/*
rm Monkey\ Joe/*
rm Monkey" "Joe/*
rm M'o'n'k'e'y J'o'e'/*
dir="Monkey Joe"; rm "$dir"/*
cd "Monkey Joe"; rm *

Perl would also work but you could face the same issues if you're
using the glob feature or system() to access the files.


William R Ward               bill at wards.net             http://bill.wards.net
   Help save the San Jose Earthquakes - http://www.soccersiliconvalley.com/

More information about the svlug mailing list