Handling files/directories with spaces in `for’-loops

Posted on Saturday, 7th July, 2007 in Life

So I have one or the other file, that needs to be extracted to a directory. And why not name it as the archive itself .. Only problem with it is the handling of variables with bash …

Try it yourself, stuff some directories with a space in inside a variables, and use something like this:

epimetheus tmp [0] $ mkdir files
epimetheus tmp [0] $ touch files/"I hate directories.archive" files/"Me luuv you looong time.archive"
epimetheus tmp [0] $ for i in $( /bin/ls --color=none files/ ); do mkdir "${i/.archive/}"; done

And now take a look at the output of that ..

epimetheus tmp [0] $ ls
I/  Me/  directories/  files/  hate/  looong/  luuv/  time/  you/

Means, the `mkdir‘ created a directory for every entry in the `ls‘ output that was separated by a space char … and I’ve no frickin clue on how to get that thing right … :mad:
Update:
Thanks to Roy I know how one handles such things … :oops: It’s rather simple *g*

epimetheus tmp [0] $ for i in files/*; do mkdir "$( basename "${i/.archive/}" )"; done

That should give you the desired effect :!:


2 Responses to “Handling files/directories with spaces in `for’-loops”


  1. ls –quoting-style=escape might help here as well


  2. The way I learned to handle spaces in file names in shell loops is to use read like:

    ls -1 | while read i; do mkdir “${i/.archive/}”; done

Leave a Reply