Bash, For loop, Files with spaces

Posted by Michael Giarlo on September 27, 2008

Dear Future Me,

Are you trying to iterate over filenames with spaces in them using a bash 'for' loop?  And instead of iterating over the filenames, you wind up seeing a list of filename parts split by said spaces?  Use case: you want to print out a list of unique extensions for all files in the current directory and below:

    for file in `find . -type f`; do echo ${file##*.}; done | sort | uniq

If any filenames have spaces in them, you may see odd results.  The answer?  Set the input field separator (IFS) environment variable to the newline character (rather than the default space character):

    export IFS=$'\n'

And voila.

Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

  1. Bill Dueber Thu, 02 Oct 2008 15:52:38 PDT

    Also useful: find with -print0 and xargs -0 to use the ASCII 0 for separating values.

    find [find args] -print0 | xargs -0 [xargs args]

    Very useful when dealing with files with spaces

  2. Gabriel Farrell Thu, 02 Oct 2008 15:54:25 PDT

    Good tip. Odds that I will remember it at a useful time are low. I'll just bug you whenever I try to do anything fancy with bash, and someday maybe you can point me back at this.

  3. Thanh Wed, 22 Oct 2008 20:51:28 PDT

    Thank you so much!

Comments