Results 1 to 3 of 3
I have a simple script to resize images in batches:
% more resize.sh
#!/bin/sh
for i in *.jpg *.JPG ; do
j=`echo $i | cut -d "." -f1`
anytopnm $i ...
- 08-16-2009 #1Just Joined!
- Join Date
- Aug 2009
- Posts
- 9
BASH "for" scripting question
I have a simple script to resize images in batches:
% more resize.sh
#!/bin/sh
for i in *.jpg *.JPG ; do
j=`echo $i | cut -d "." -f1`
anytopnm $i > $j.ppm
pnmscale 0.5 $j.ppm > $j.small.ppm
pnmtojpeg -quality=95 $j.small.ppm > $j.small.jpg
rm *.ppm
done
The script works, except I also get an empty file called "*.small.jpg"
If I add echo statements:
#!/bin/sh
for i in *.jpg *.JPG ; do
echo $i
j=`echo $i | cut -d "." -f1`
echo $j
done
I get what I think I should get -- the filename and the cut filename, but as the last output, I get an entire directory listing (including folders and non-jpg stuff):
DSC_7081.small.jpg
DSC_7081
DSC_7082.small.jpg
DSC_7082
DSC_7083.small.jpg
DSC_7083
.
.
.
DSC_7081.small.jpg DSC_7082.small.jpg DSC_7083.small.jpg DSC_7084.small.jpg ...rest of directory
I do not understand why I get this last output, or the "*.small.jpg" file. Can someone explain to me why "*" is appended to this list?
Thanks!
billo
- 08-17-2009 #2Linux User
- Join Date
- May 2008
- Location
- NYC, moved from KS & MO
- Posts
- 251
1. For *.small.jpg problem, check if you have a file named "*.jpg", delete it with rm "*.jpg" if so. [ Be careful, it's rm "*.jpg", not rm *.jpg, the latter will delete all files ending with .jpg including a file named "*.jpg", which is also a legal file name .]
2. Using for loop like you do in your script will result in directories being processed as well if the directory name contains jpg or JPG in the end, which sometimes can cause unexpected result. A better way is to use find command like this
3. You don't need to use cut in order to get the file name without the jpg or JPG extensions. Bash supports string manipulation operations (just google it). In your script you can get the base name like thisCode:cd to_the_target_dir find . -type f -iname "*.jpg"
j=${i%.*}
4. By combining 2 and 3, you can rewrite your script like this:
( Of course this not the only way to solve the problem. )
Code:find . type f -iname "*.jpg" | while read i; do j=${i%.*} [ the rest of the converting codes ] done
- 08-17-2009 #3Just Joined!
- Join Date
- Aug 2009
- Posts
- 9
Thanks for the response, especially about stripping extensions.
No, I don't *originally* have a file named "*.small.jpg" in my directory -- the script *creates* one that I must subsequently delete
It's clear that the last $j is "*" -- in the original script, it creates "*.small.jpg" and in the modified script, it echoes the listing of "*".
As an aside, if I replace "cut" with the bash command you gave me, it does the same thing (though more elegantly...)
billo


Reply With Quote