Bash for loop with files containing white space

Transfered from Linux Config Disqus comments:

Question: i’ve got a problem when using wild cards like “*.jpg”. maybe you have a hint for that resp. want to add an example for the community:

  • there is a directory with files,that also have spaces in the name
  • i want to write a script that creates thumbs from its jpgs (using mogrify)
  • if i call the script with arg “*.jpg” then the names are resolved as space delimitered strings
  • inside the script i can’t find out anymore, if space is a delimiter or part of the name

What i found is an option in ls “-b” that escapes the spaces. This could be the solution. Is there a way to resolve “*.jpg” in a escaped way?
Answer:
You may want to set $IFS ( Internal Field Separator ) variable to avoid your for loops break when encountered with a whitespace character such as space or tabs.
I have written a small script for you to match your scenario ( that is, if I interpreted your question correctly ). I have tested this script to create thumbnails inside a directory containing *.jpg" images with a space within a file name.


WARNING:
The script below will overwrite your existing files !!! Do not execute if you are not sure what you are doing.


#!/bin/bash 
 
IFS=$(echo -en "
\b") 
 
for image in $( ls *.jpg ) ; do 
        mogrify -geometry 100x65 $image 
done 

Hope this helps…