Today, while working with a project to import thousands of articles from text files to wordpress, I had faced a trouble while I am executing a shell script to iterate through all text files and call a PHP script with sending the filename as argument. The PHP script would then process the file as our requirement. The shell script looked like:
for i in `find . -type f -name '*.txt'`;
php import_posts.php $i
Here, $i would be the filename and it is passed to PHP script for processing. But the problem is that, when the filename (including directory name) consists any whitespace in its name, the script would broken. For example, some files path looked like
/home/user/articles/Internet Business/Web Hosting/how_to_start_your_company.txt
Here, notice the space after Internet and Web. The shell script was breaking just after Internet. It was sending /home/user/articles/Internet as argument to PHP script and obviously PHP script was failed to find this file.
After searching a lot, finally I found a solution.
It was really simple. I am quoting from his blog:
If none of your files or folders have spaces in their names, then this isn’t a problem, but that is increasingly unlikely nowadays. If your songs do have spaces in their filenames, then the solution is to change how the shell splits that output. This is controlled by the variable $IFS, which is set to spaces, tabs, and newlines by default. We’d like it set to just newlines, so we do:
So, here is the solution. I just put the following line at the top of my shell script.
After that everything is fine. The script is running exactly how I intended it to run.
Thanks for Anthony for his solution.