I can’t take credit for this. Stuart Jansen of Guru Labs referenced Tensai‘s brilliance (nice play on words Stuart. For thoes who don’t know, ‘tensai’ in Japanese means smart or brilliant). Tensai is one of the members of PLUG and is also on irc.freenode.net’s #utah most of the time. Tensai in turn blames Hans Fugal for actually pointing him in the direction of this solution. And so we find that knowledge always exists, not unlike matter, neither destroyed or created, just changing forms. I wanted to get this down in my blog because it’s a good place to have ideas which are useful and hopefully it will help someone else.
Often one needs to process files which may contain spaces in them in a bash script. There are various ways to do this however, this is the simplest and most clean way that I have found to do this. This method uses the ‘read’ command which reads and entire line of text into a single variable. This varialble can then be quoted which protects the spaces as you process the files. Very simple and clean:
find | while read I; do echo "$I"; done
So, to copy some mp3s to a backup directory:
find /path/to/files/ -iname "*mp3" | \ while read I; do cp -v --parent "$I" /backup/dir/ done
This will copy all mp3 files under
/path/to/files/ with their parent directory structure intact to
Keywords: Linux, bash scripting, linux scripting, unix scripting, bash shell, shell scripting, unix shell programming, OSX.