BASH arrays and filenames with spaces

I'm sure I can use this one quite often.

1) Arrays are nice to avaoid temporaray files

2) Spaces in file names are a PITA. But there are nice ways to work around this

Array[0]="/some/path/to/mooo foo.txt"
Array[1]="/some/path/to/mooo foo bar 2.txt"
Array[2]="/some/path/to/mooo foo bar 3.txt"

There we have some example array.

for ((i=0;i<${#Array[@]};i++)); do echo ${Array[$i]}; done
/some/path/to/mooo foo.txt
/some/path/to/mooo foo bar 2.txt
/some/path/to/mooo foo bar 3.txt

Ok, now what if want to pass that to ls, we could quote it somehow. Or use some pattern expansion to replace the space with backslash space, like

for ((i=0;i<${#Array[@]};i++)); do echo ${Array[$i]// /\\ }; done
/some/path/to/mooo\ foo.txt
/some/path/to/mooo\ foo\ bar\ 2.txt
/some/path/to/mooo\ foo\ bar\ 3.txt

Great! Another way would be to temporarily change the special variable $IFS that determines which character is used for word splitting. Let's set this to "newline"

OLDIFS="$IFS"
IFS=$'\n'

for ((i=0;i<${#Array[$i]};i+=1)); do
   ls ${Array[$i]}
done

IFS="$OLDIFS"

That $IFS change can also be used in all sorts of other loops. Hell, I'm going to need that really often. Thanks to the guys on http://forums.gentoo.org/viewtopic-t-714971.html

Category: