Cycle through file names containing spaces in Bash

If you have a long list of file names and some of them contain spaces, in a Bash “for” cycle you would end up with the names split in several entries, for example:

$ $ ls -1 tmp/
Another file with spaces
File 1 with spaces
$ for F in $(ls -1 tmp) ; do echo $F ; done
Another
file
with
spaces
File
1
with
spaces

Manipulating the Bash Internal Field Separator (as detailed in the Advanced Bash Scripting Guide), we can tell Bash to ignore spaces:

$ IFS="$(printf '\n\t')"
$ for F in $(ls -1 tmp) ; do echo $F ; done
Another file with spaces
File 1 with spaces

I suggest you save your IFS in another variable before changing it, so you can restore it after you’re done.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s