SubZeroFX
SubZeroFX

Reputation: 490

bash: White-space in filenames

I've got a simple script:

#!/bin/sh
cd /tmp/pics
for pic in *.jpg;
do
  php -f /tmp/pics/covert.php $pic;
done

When my pictures have white-space in their names that script won't work. How could I fix that?

How can I fix my script to handle whitespace properly, and also handle other JPEG extensions, such as "JPG", "JPEG", "jpeg"?

Upvotes: 0

Views: 316

Answers (3)

iconoclast
iconoclast

Reputation: 22610

Quoting rules in bash and other shells are unlike those in "normal" scripting languages like Ruby and Python and Perl, so this may be confusing at first, but if you put double quotes around $pic, bash will treat the contents of the variable properly even if it contains spaces.

That one fix would make your script look like this

#!/bin/sh
cd /tmp/pics
for pic in *.jpg;
do
  php -f /tmp/pics/covert.php "$pic";
done

I would also remove the semi-colons at the end of each line. Those are only needed if you're cramming multiple lines together on one line. They're not needed in bash the way they are in PHP or (to a lesser extent) JavaScript.

As written, this is using the Bourne shell instead of bash. (For the moment we'll ignore the fact that bash might be used on your system to emulate the Bourne shell.) Change the "shebang" line at the top if you want to use bash. Typically it is #!/bin/bash.

To handle multiple file extensions, you can just stack them up next to each other with spaces in between, like this

for pic in *.jpg *.jpeg *.JPEG *.JPG

As Jens points out, you might have odd corner-cases where the file extension is mixed case. You can handle that with brackets to group characters

for pic in *.[jJ][pP][gG] *.[jJ][pP][eE][gG]

or you could use glenn's approach of setting your shell options to ignore case (and non-matching patterns) and then use a simpler glob pattern

shopt -s nocaseglob nullglob
for pic in *.jpg *.jpeg

If we take that latter approach, the final script would look like this:

#!/bin/bash
cd /tmp/pics
shopt -s nocaseglob nullglob
for pic in *.jpg *.jpeg
do
  php -f /tmp/pics/covert.php "$pic"
done

Hope this helps!

Upvotes: 2

glenn jackman
glenn jackman

Reputation: 246799

With bash, to do case-insensitive file matching:

shopt -s nocaseglob nullglob
for pic in *{jpg,jpeg}
do
    php5 -f ./convert.php "$pic"
done

Upvotes: 2

Jens
Jens

Reputation: 72639

For short scripts like this I would use

#!/bin/sh
cd /tmp/pics
for pic in *.[jJ][pP][gG] *.[jJ][pP][eE][gG]; do
  php -f /tmp/pics/covert.php "$pic"
done

This handles even weird camelcasing extensions like prettygirl.JpeG :-)

Upvotes: 2

Related Questions