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”?
Quoting rules in
bashand 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
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
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
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
If we take that latter approach, the final script would look like this:
Hope this helps!