MacOS终端按ID匹配图片复制至新目录失败求助
问题根源
你的脚本核心错误在于依赖find命令的退出码判断是否找到文件——find只要自身执行无异常(比如目录存在、权限正常),哪怕没有匹配到任何文件,都会返回退出码0。这就导致不管有没有找到对应图片,脚本都会输出"匹配成功"的提示,而实际没找到文件时cp根本没执行,自然不会有图片被复制。
修复方案
这里提供两种适配你场景的可靠修复方式:
方案1:通过find输出判断匹配结果
捕获find的输出内容,只有当输出非空时,才判定找到文件并提示成功:
img_dir=./images new_img_dir=./new_images if [ ! -d "$new_img_dir" ] then mkdir "$new_img_dir" chmod -R 755 "$new_img_dir" fi while IFS= read -r id; do # 捕获find的输出,用于判断是否有匹配 match_result=$(find "$img_dir" -maxdepth 1 -iname "$id.*" -print -exec cp -v {} "$new_img_dir" \;) if [ -n "$match_result" ]; then echo "ID: $id" echo "Match found and copied to $new_img_dir" else echo "No match found for ID: $id" fi done < "ids.txt"
方案2:直接用cp匹配(更高效)
因为你限定了只在images根目录查找(-maxdepth 1),完全可以跳过find,用cp的通配符直接匹配,逻辑更直观:
img_dir=./images new_img_dir=./new_images if [ ! -d "$new_img_dir" ] then mkdir "$new_img_dir" chmod -R 755 "$new_img_dir" fi while IFS= read -r id; do # 用cp直接匹配,2>/dev/null屏蔽"无匹配文件"的错误提示 cp -v "$img_dir/$id".* "$new_img_dir" 2>/dev/null if [ $? -eq 0 ]; then echo "ID: $id - Match found and copied to $new_img_dir" else echo "ID: $id - No match found" fi done < "ids.txt"
额外优化建议
- 给所有路径变量加上双引号(比如
"$new_img_dir"),避免目录名包含空格或特殊字符时出现异常; - 方案2效率更高,无需启动额外的
find进程,直接用Shell内置的通配符匹配逻辑。
内容的提问来源于stack exchange,提问作者Roger
相关产品推荐
相关产品推荐

