我正在尝试编写脚本,以裁剪和调整大的照片到高清壁纸。
#! /bin/bash
for i in `ls *.jpg`
do
width=`identify -format '%w' $i`
height=`identify -format '%h' $i`
if [ `echo "$width/$height > 16/9" | bc -l` ]
then
exec `convert $i -resize 1920 -gravity Center -crop '1920x1080+0+0' +repage temp`
else
exec `convert $i -resize x1080 -gravity Center -crop 1920x1080+0+0 +repage temp`
fi
rm $i
mv temp $i
done
但是该脚本似乎在文件名中包含空格(如Tumble Weed.jpg)时存在问题。我该如何解决这个问题呢?
发布于 2010-10-19 19:19:17
首先,您不需要ls
。通过在backtics中使用ls
,您可以隐式地让bash将一个字符串解析为一个列表,该列表按空格拆分。取而代之的是,让bash生成列表并将其分开,而不需要这样的怪癖:
此外,您需要将所有$i
用法都用引号括起来,使bash将其作为一个整体进行替换,而不是将其作为字符串拆分为单独的单词。
下面是演示这两种想法的脚本:
for i in *.jpg ; do
echo "$i";
done
发布于 2010-10-19 19:16:35
使用read来规避空格的问题。像这样编写循环看起来有点不自然,但它工作得更好:
find . -type f -iname "*.jpg" | while read i
do
# your original code inside the loop using "$i" instead of $i
done
在-iname
中,你也可以得到像.JPG这样具有不同大小写的扩展名的jpg文件。
发布于 2010-10-19 19:13:59
我建议这样写for-line:
for i in *.jpg
并将$i
封装在双引号中:"$i"
。
如果你坚持
`ls *.jpg`
样式,(例如,如果您从更复杂的命令中获取文件名),您可以尝试将IFS
设置为\n
IFS='\n'
比较这两个执行:
$ for f in `ls *`; do echo $f; done
hello
world
test
$ IFS='\n'; for f in `ls *`; do echo $f; done
hello world
test
https://stackoverflow.com/questions/3967707
复制相似问题