Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

Handling filenames with spaces in a bash for or while loop (See related posts)

// The `find` here gets every directory in my home dir, one level deep, but some of them have spaces... the default 'for i in $(find ...)' behavior treats each individual word boundary as a separate variable, but piping to `read` breaks them on newlines
// Note: OS X `find` does not support "-depth 1" (its -depth opt is for depth-first searching vs. breadth-first), just use an 'ls' with an 'if [ -d $filename]' to test for directories

find ~ -type d -depth 1 | while read filename; do
# ls ~ | while read filename; do
        echo $filename
        # other stuff
done

Comments on this post

Araxia posts on Jun 28, 2007 at 19:47
In bash, you can just set the internal field separator (IFS) to not include spaces and you'll be able to use paths with spaces in them, e.g.

#!/bin/bash
FOOBAR="/System/Library/Screen Savers/"
echo "Test #1 with default IFS:"
ls ${FOOBAR}
ORIGINAL_IFS=$IFS
IFS=$'\n'
echo ""
echo "Test #2 with modified IFS:"
ls ${FOOBAR}
IFS=$ORIGINAL_IFS
echo ""
echo "Test #3 with restored IFS:"
ls ${FOOBAR}


Note that the $ before the '\n' is just so the \n sequence is treated as a single character.

You need to create an account or log in to post comments to this site.


Related Posts