如何用for命令循环处理大小写扩展名的JPG文件并修正扩展名
解决JPG大小写扩展名的处理问题
你的核心问题在于shell参数扩展不支持${i%%.{jpg,JPG}}这种多扩展名匹配写法,导致无法正确移除.jpg/.JPG扩展名,进而生成错误的文件名。以下是修复后的完整函数:
imow() { clear local i DIMENSIONS temp_dir mpc_file # 开启nullglob:当没有匹配的文件时,不会保留*.jpg这类无效字符串 shopt -s nullglob # 遍历所有jpg/JPG文件 for i in *.{jpg,JPG} do # 创建临时目录(避免使用RANDOM作为变量名,它是bash内置随机数变量) temp_dir="$(mktemp --directory)" # 获取文件名主体:移除最后一个.及后面的所有内容(适配大小写扩展名) local base_name="${i%.*}" echo -e "\nCreating two temporary cache files: ${temp_dir}/${base_name}.mpc + ${temp_dir}/${base_name}.cache\n" DIMENSIONS="$(identify -format '%wx%h' "${i}")" convert "${i}" -monitor -filter 'Triangle' -define filter:support='2' -thumbnail "${DIMENSIONS}" -strip \ -unsharp '0.25x0.08+8.3+0.045' -dither None -posterize '136' -quality '82' -define jpeg:fancy-upsampling='off' \ -define png:compression-filter='5' -define png:compression-level='9' -define png:compression-strategy='1' \ -define png:exclude-chunk='all' -auto-level -enhance -interlace 'none' -colorspace 'sRGB' "${temp_dir}/${base_name}.mpc" clear # 内层循环改用mpc_file,避免覆盖外层的文件名变量i for mpc_file in "${temp_dir}"/*.mpc do if [ -f "${mpc_file}" ]; then echo -e "\nOverwriting original file with optimized self: ${mpc_file} >> ${base_name}.jpg\n" convert "${mpc_file}" -monitor "${temp_dir}/${base_name}.jpg" if [ -f "${temp_dir}/${base_name}.jpg" ]; then mv "${temp_dir}/${base_name}.jpg" "${PWD}" rm -fr "${temp_dir}" clear else clear echo 'Error: Unable to find the optimized image and therefore can'\''t overwrite the original.' echo exit 1 fi fi done done # 关闭nullglob,恢复shell默认行为 shopt -u nullglob }
关键修复说明
- 扩展名处理:
${i%.*}是shell标准参数扩展语法,会移除文件名最后一个.及其之后的所有内容,完美适配.jpg和.JPG两种大小写扩展名,直接得到纯净的文件名主体。 - 避免无效匹配:
shopt -s nullglob确保当目录中没有对应扩展名的文件时,循环不会执行,也不会出现*.jpg这类无效文件名。 - 变量名规范:替换了原函数中误用的
RANDOM变量名(它是bash内置随机数变量),改用temp_dir避免冲突。 - 变量覆盖修复:内层循环使用
mpc_file代替i,防止覆盖外层循环的文件名变量,避免后续逻辑出错。
内容的提问来源于stack exchange,提问作者slyfox1186
相关产品推荐
相关产品推荐

