← All Exercises
Batch Rename Photos with a Dry Run
intermediatebash
Background
Bulk renames are easy to get wrong. A dry-run default, nullglob, and collision checks make the operation reviewable before any file moves.
Problem
Write a script that renames every IMG_*.jpeg file in a directory to photo-001.jpeg, photo-002.jpeg, and so on. Without --apply it must only print the planned renames.
Input
A directory path and an optional second argument --apply. Matching files must start with IMG_ and end with .jpeg.
Output
Dry run prints would rename <source> -> <target>; --apply performs the move and prints renamed <source> -> <target>; a target collision exits non-zero.
Sample tests
Sample 1
Input: /photos containing IMG_2024.jpeg and IMG_2025.jpeg, run without --apply
Expected: would rename /photos/IMG_2024.jpeg -> /photos/photo-001.jpeg would rename /photos/IMG_2025.jpeg -> /photos/photo-002.jpeg
Sample 2
Input: the same directory, run with --apply
Expected: renamed /photos/IMG_2024.jpeg -> /photos/photo-001.jpeg renamed /photos/IMG_2025.jpeg -> /photos/photo-002.jpeg
Your solution
Learning objective
Use nullglob, arrays, printf -v, collisions checks, and a dry-run switch for safe bulk file operations.